Инвентаризация через Keenetic: 106 устройств и вход в KeeneticOS 5
Реализован вход по схеме x-ndw2-interactive (challenge + sha256), доступ в /root/.keenetic.json (600). Модель Hopper SE, KeeneticOS 5.01. Собраны все зарегистрированные клиенты (106) с именами; инвентарь записан в ядро (коллекция devices). Найдены телевизоры: два Chromecast («Гостиная», «Smart TV Pro»), Samsung, Xiaomi, Hisense и «тв Родители кабинет» — четыре из них выключены, поэтому IP неизвестны. Колонки Яндекса: Lite и Midi. Ловушки: рабочий путь /rci/ip/dhcp (без show); offline-устройства отдают 0.0.0.0; второй роутер .63 недоступен.
This commit is contained in:
1 parent
0bfb13ddf1
commit
2c86d3d0e4
5 files changed
+487
No files matched your search
@@ -0,0 +1,60 @@
|
||||
# Инвентаризация сети через Keenetic
|
||||
|
||||
Роутер: **Keenetic Hopper SE**, KeeneticOS 5.01.C.5.0-0, `http://192.168.1.1`.
|
||||
|
||||
## Вход
|
||||
|
||||
KeeneticOS 5 использует схему `x-ndw2-interactive`, а не Basic/Digest:
|
||||
|
||||
1. `GET /auth` → заголовки `X-NDM-Challenge`, `X-NDM-Realm` + cookie.
|
||||
2. `md5 = md5(login:realm:password)`
|
||||
3. `sha = sha256(challenge + md5)`
|
||||
4. `POST /auth {"login": ..., "password": sha}` с той же cookie.
|
||||
5. Дальше `/rci/...` с cookie.
|
||||
|
||||
Доступ хранится в `/root/.keenetic.json` (600). Проверено: модель
|
||||
`Hopper SE`, версия `5.01.C.5.0-0`.
|
||||
|
||||
## Эндпоинты
|
||||
|
||||
| Путь | Что отдаёт |
|
||||
|---|---|
|
||||
| `/rci/show/version` | модель, версия |
|
||||
| `/rci/show/ip/hotspot` | **все зарегистрированные клиенты** с именами |
|
||||
| `/rci/ip/dhcp` | DHCP-пулы и активные аренды |
|
||||
| `/rci/show/interface` | интерфейсы, WAN |
|
||||
| `/rci/ip/static` | проброс портов |
|
||||
|
||||
Важно: `/rci/**show**/ip/dhcp` возвращает пустой список — рабочий путь без
|
||||
`show`: `/rci/ip/dhcp`.
|
||||
|
||||
## Что нашлось: 106 устройств
|
||||
|
||||
Телевизоры (по MAC и именам):
|
||||
|
||||
| MAC | Бренд | Имя / статус |
|
||||
|---|---|---|
|
||||
| c4:8b:66 | Chromecast | **«Гостиная»** 192.168.1.147 |
|
||||
| 14:ea:63 | Chromecast | **«Smart TV Pro»** 192.168.1.149 |
|
||||
| 44:ea:30 | Samsung | телевизор, сейчас выключен |
|
||||
| 7c:49:eb | Xiaomi | телевизор, сейчас выключен |
|
||||
| e8:51:77 | Qingdao (Hisense) | телевизор, сейчас выключен |
|
||||
| 48:9e:9d | Hui Zhou Gaoshengda | **«тв Родители кабинет»**, выключен |
|
||||
|
||||
Колонки: `yandex-station-lite` (192.168.1.35),
|
||||
`Yandex-Station-Midi-REWK` (192.168.1.49).
|
||||
|
||||
Прочее: PlayStation 5 (d4:f7:d5), PICO 4 (Goertek), ESP-127791 (Espressif),
|
||||
Deerma увлажнитель, Dreame робот-пылесос, Careli фритюрница, Tuya-устройство,
|
||||
телефоны (S25 Ultra, HUAWEI P20, Realme), ноутбуки, steamdeck.
|
||||
|
||||
## Ловушки
|
||||
|
||||
1. **Offline-устройства отдают `0.0.0.0`.** Keenetic хранит имена всех
|
||||
клиентов, но IP только у активных. Чтобы получить IP телевизора, он должен
|
||||
быть включён.
|
||||
2. **Второй роутер недоступен.** `192.168.1.63` («Роутер Родители») — no route
|
||||
to host; `192.168.1.3` («роутер Кабинет») отвечает, но клиентов 0.
|
||||
3. **`nextcloudpi` попал в фильтр «тв»** по подстроке — фильтр по имени надо
|
||||
проверять глазами.
|
||||
4. **Прошивка 5.x** — старые примеры с `/rci/show/ip/dhcp` не работают.
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Полный инвентарь Keenetic: клиенты с IP, именами и фильтрами."""
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://192.168.1.1"
|
||||
CREDS = "/root/.keenetic.json"
|
||||
|
||||
|
||||
def session():
|
||||
d = json.load(open(CREDS, encoding="utf-8"))
|
||||
login, password = d["login"], d["password"]
|
||||
jar = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
try:
|
||||
r = op.open(urllib.request.Request(BASE + "/auth"), timeout=10)
|
||||
ch, realm = r.headers.get("X-NDM-Challenge"), r.headers.get("X-NDM-Realm")
|
||||
except urllib.error.HTTPError as e:
|
||||
ch, realm = e.headers.get("X-NDM-Challenge"), e.headers.get("X-NDM-Realm")
|
||||
md5 = hashlib.md5(f"{login}:{realm}:{password}".encode()).hexdigest()
|
||||
sha = hashlib.sha256((ch + md5).encode()).hexdigest()
|
||||
body = json.dumps({"login": login, "password": sha}).encode()
|
||||
op.open(urllib.request.Request(BASE + "/auth", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json"}), timeout=10)
|
||||
return op
|
||||
|
||||
|
||||
def get(op, path):
|
||||
try:
|
||||
with op.open(urllib.request.Request(BASE + path), timeout=20) as r:
|
||||
raw = r.read()
|
||||
return (json.loads(raw) if raw else {}), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def collect(op):
|
||||
dhcp, _ = get(op, "/rci/ip/dhcp")
|
||||
live, _ = get(op, "/rci/show/ip/hotspot")
|
||||
|
||||
leases = (dhcp or {}).get("host") or []
|
||||
if isinstance(leases, dict):
|
||||
leases = list(leases.values())
|
||||
hosts = (live or {}).get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
|
||||
live_mac = {}
|
||||
for h in hosts:
|
||||
live_mac[(h.get("mac") or "").lower()] = h
|
||||
|
||||
rows = []
|
||||
seen = set()
|
||||
for h in leases:
|
||||
mac = (h.get("mac") or "").lower()
|
||||
seen.add(mac)
|
||||
l = live_mac.get(mac, {})
|
||||
ip = l.get("ip") or h.get("ip") or ""
|
||||
name = l.get("name") or h.get("name") or l.get("hostname") or "—"
|
||||
name = name.split(" - Home network")[0]
|
||||
rows.append({"ip": ip, "mac": mac, "name": name,
|
||||
"online": bool(l), "iface": (l.get("interface") or {}).get("id") if isinstance(l.get("interface"), dict) else ""})
|
||||
for mac, l in live_mac.items():
|
||||
if mac in seen:
|
||||
continue
|
||||
name = (l.get("name") or l.get("hostname") or "—")
|
||||
name = name.split(" - Home network")[0]
|
||||
rows.append({"ip": l.get("ip") or "", "mac": mac, "name": name,
|
||||
"online": True, "iface": (l.get("interface") or {}).get("id") if isinstance(l.get("interface"), dict) else ""})
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
op = session()
|
||||
rows = collect(op)
|
||||
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else "--all"
|
||||
if mode == "--online":
|
||||
rows = [r for r in rows if r["online"]]
|
||||
elif mode == "--tv":
|
||||
keys = ("тв", "tv", "телевизор", "samsung", "lg", "sony", "philips", "tcl", "hisense", "xiaomi", "sharp", "panasonic")
|
||||
rows = [r for r in rows if any(k in (r["name"] or "").lower() for k in keys)]
|
||||
elif mode == "--speakers":
|
||||
keys = ("станция", "алиса", "yandex", "мини", "лайт", "макс", "колонка")
|
||||
rows = [r for r in rows if any(k in (r["name"] or "").lower() for k in keys)]
|
||||
|
||||
print(f" устройств: {len(rows)}")
|
||||
for r in sorted(rows, key=lambda x: x["name"].lower()):
|
||||
ip = r["ip"] or "—"
|
||||
mark = "●" if r["online"] else "○"
|
||||
print(f" {mark} {ip:<16} {r['mac']:<18} {r['name'][:48]}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,216 @@
|
||||
"""Инвентаризация Keenetic Hopper SE: DHCP-аренды, Wi-Fi, WAN.
|
||||
|
||||
Схема входа (x-ndw2-interactive):
|
||||
1. GET /auth → X-NDM-Challenge, X-NDM-Realm, cookie
|
||||
2. md5 = md5(login:realm:password); sha = sha256(challenge + md5)
|
||||
3. POST /auth {"login":..., "password": sha} с той же cookie
|
||||
4. дальше /rci/... с cookie
|
||||
|
||||
Команды:
|
||||
--login ЛОГИН --password ПАРОЛЬ сохранить доступ
|
||||
--leases клиенты DHCP
|
||||
--wifi клиенты Wi-Fi
|
||||
--status модель, версия, WAN
|
||||
"""
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://192.168.1.1"
|
||||
CREDS = "/root/.keenetic.json"
|
||||
|
||||
|
||||
def stored():
|
||||
try:
|
||||
d = json.load(open(CREDS, encoding="utf-8"))
|
||||
return d.get("login"), d.get("password")
|
||||
except Exception:
|
||||
return None, None
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self, login, password):
|
||||
self.login = login
|
||||
self.password = password
|
||||
self.jar = http.cookiejar.CookieJar()
|
||||
self.opener = urllib.request.build_opener(
|
||||
urllib.request.HTTPCookieProcessor(self.jar))
|
||||
|
||||
def raw_get(self, path):
|
||||
req = urllib.request.Request(BASE + path, headers={"Accept": "application/json"})
|
||||
return self.opener.open(req, timeout=15)
|
||||
|
||||
def login_now(self):
|
||||
try:
|
||||
resp = self.raw_get("/auth")
|
||||
challenge = resp.headers.get("X-NDM-Challenge")
|
||||
realm = resp.headers.get("X-NDM-Realm")
|
||||
except urllib.error.HTTPError as e:
|
||||
# 401 — это нормально, заголовки есть
|
||||
challenge = e.headers.get("X-NDM-Challenge")
|
||||
realm = e.headers.get("X-NDM-Realm")
|
||||
if not challenge or not realm:
|
||||
return "нет challenge"
|
||||
|
||||
md5 = hashlib.md5(f"{self.login}:{realm}:{self.password}".encode()).hexdigest()
|
||||
sha = hashlib.sha256((challenge + md5).encode()).hexdigest()
|
||||
body = json.dumps({"login": self.login, "password": sha}).encode()
|
||||
req = urllib.request.Request(BASE + "/auth", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json"})
|
||||
try:
|
||||
with self.opener.open(req, timeout=15) as r:
|
||||
if r.status == 200:
|
||||
return None
|
||||
return f"HTTP {r.status}"
|
||||
except urllib.error.HTTPError as e:
|
||||
return f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return str(e)[:80]
|
||||
|
||||
def get(self, path):
|
||||
try:
|
||||
with self.raw_get(path) as r:
|
||||
raw = r.read()
|
||||
if not raw:
|
||||
return [], None
|
||||
try:
|
||||
return json.loads(raw), None
|
||||
except Exception:
|
||||
return raw.decode("utf-8", "replace"), None
|
||||
except urllib.error.HTTPError as e:
|
||||
return None, f"HTTP {e.code}"
|
||||
except Exception as e:
|
||||
return None, str(e)[:100]
|
||||
|
||||
|
||||
def inventory(c):
|
||||
"""Сводка: аренды + подключённые, с именами."""
|
||||
dhcp, _ = c.get("/rci/ip/dhcp")
|
||||
live, _ = c.get("/rci/show/ip/hotspot")
|
||||
|
||||
leases = (dhcp or {}).get("host") or []
|
||||
if isinstance(leases, dict):
|
||||
leases = list(leases.values())
|
||||
hosts = (live or {}).get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
|
||||
live_by_mac = {}
|
||||
for h in hosts:
|
||||
live_by_mac[(h.get("mac") or "").lower()] = h
|
||||
|
||||
rows = []
|
||||
seen = set()
|
||||
for h in leases:
|
||||
mac = (h.get("mac") or "").lower()
|
||||
seen.add(mac)
|
||||
l = live_by_mac.get(mac, {})
|
||||
rows.append({
|
||||
"ip": h.get("ip") or h.get("address"),
|
||||
"mac": mac,
|
||||
"name": (l.get("name") or h.get("name") or l.get("hostname") or "—"),
|
||||
"hostname": l.get("hostname") or "",
|
||||
"online": bool(l),
|
||||
"interface": ((l.get("interface") or {}).get("id")
|
||||
if isinstance(l.get("interface"), dict) else ""),
|
||||
})
|
||||
for mac, l in live_by_mac.items():
|
||||
if mac in seen:
|
||||
continue
|
||||
rows.append({
|
||||
"ip": l.get("ip"), "mac": mac,
|
||||
"name": l.get("name") or l.get("hostname") or "—",
|
||||
"hostname": l.get("hostname") or "",
|
||||
"online": True,
|
||||
"interface": ((l.get("interface") or {}).get("id")
|
||||
if isinstance(l.get("interface"), dict) else ""),
|
||||
})
|
||||
return rows
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if not args:
|
||||
print(__doc__)
|
||||
return 0
|
||||
|
||||
login, password = stored()
|
||||
if args[0] == "--login":
|
||||
login = args[args.index("--login") + 1]
|
||||
password = args[args.index("--password") + 1]
|
||||
|
||||
if not login:
|
||||
print("нет доступа: запустите --login ЛОГИН --password ПАРОЛЬ")
|
||||
return 1
|
||||
|
||||
c = Client(login, password)
|
||||
err = c.login_now()
|
||||
if err:
|
||||
print(" вход не удался:", err)
|
||||
return 1
|
||||
|
||||
if args[0] == "--login":
|
||||
with open(CREDS, "w", encoding="utf-8") as f:
|
||||
json.dump({"login": login, "password": password}, f)
|
||||
os.chmod(CREDS, 0o600)
|
||||
v, _ = c.get("/rci/show/version")
|
||||
print(" вход выполнен. Модель:", (v or {}).get("device") or (v or {}).get("title"))
|
||||
return 0
|
||||
|
||||
if args[0] == "--leases":
|
||||
d, err = c.get("/rci/ip/dhcp")
|
||||
if err:
|
||||
print(" ошибка:", err)
|
||||
return 1
|
||||
hosts = (d or {}).get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
print(f" аренд: {len(hosts)}")
|
||||
for h in sorted(hosts, key=lambda x: str(x.get("ip") or x.get("address"))):
|
||||
ip = h.get("ip") or h.get("address")
|
||||
print(f" {str(ip):<16} {h.get('mac','—'):<18} {h.get('name') or '—'}")
|
||||
return 0
|
||||
|
||||
if args[0] == "--wifi":
|
||||
d, err = c.get("/rci/show/ip/hotspot")
|
||||
if err:
|
||||
print(" ошибка:", err)
|
||||
return 1
|
||||
hosts = (d or {}).get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
print(f" Wi-Fi клиентов: {len(hosts)}")
|
||||
for h in hosts:
|
||||
print(f" {h.get('ip','—'):<16} {h.get('mac','—'):<18} {h.get('name') or '—'}")
|
||||
return 0
|
||||
|
||||
if args[0] == "--inventory":
|
||||
rows = inventory(c)
|
||||
online = sum(1 for r in rows if r["online"])
|
||||
print(f" всего устройств: {len(rows)} (в сети: {online})")
|
||||
for r in sorted(rows, key=lambda x: str(x.get("ip"))):
|
||||
mark = "●" if r["online"] else "○"
|
||||
print(f" {mark} {str(r.get('ip')):<16} {r['mac']:<18} "
|
||||
f"{str(r.get('name'))[:45]:<45} {r.get('interface') or ''}")
|
||||
return 0
|
||||
|
||||
if args[0] == "--status":
|
||||
v, _ = c.get("/rci/show/version")
|
||||
i, _ = c.get("/rci/show/interface")
|
||||
print(" модель:", (v or {}).get("device"), "| версия:", (v or {}).get("release"))
|
||||
if isinstance(i, dict):
|
||||
for name, info in i.items():
|
||||
if "WAN" in name or name.startswith(("PPPoE", "ISP")):
|
||||
print(f" {name}: up={info.get('up')} address={info.get('address')} "
|
||||
f"speed={info.get('speed')}")
|
||||
return 0
|
||||
|
||||
print(__doc__)
|
||||
return 2
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,52 @@
|
||||
"""Сопоставляет MAC телевизоров с IP из DHCP-аренд Keenetic."""
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
BASE = "http://192.168.1.1"
|
||||
CREDS = json.load(open("/root/.keenetic.json", encoding="utf-8"))
|
||||
|
||||
jar = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
try:
|
||||
r = op.open(urllib.request.Request(BASE + "/auth"), timeout=10)
|
||||
ch, realm = r.headers.get("X-NDM-Challenge"), r.headers.get("X-NDM-Realm")
|
||||
except urllib.error.HTTPError as e:
|
||||
ch, realm = e.headers.get("X-NDM-Challenge"), e.headers.get("X-NDM-Realm")
|
||||
md5 = hashlib.md5(f"{CREDS['login']}:{realm}:{CREDS['password']}".encode()).hexdigest()
|
||||
sha = hashlib.sha256((ch + md5).encode()).hexdigest()
|
||||
op.open(urllib.request.Request(BASE + "/auth",
|
||||
data=json.dumps({"login": CREDS["login"], "password": sha}).encode(),
|
||||
method="POST", headers={"Content-Type": "application/json"}), timeout=10)
|
||||
|
||||
|
||||
def get(path):
|
||||
with op.open(urllib.request.Request(BASE + path), timeout=20) as r:
|
||||
return json.loads(r.read() or b"{}")
|
||||
|
||||
|
||||
dhcp = get("/rci/ip/dhcp")
|
||||
hosts = dhcp.get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
|
||||
TARGETS = {
|
||||
"44:ea:30": "Samsung",
|
||||
"7c:49:eb": "Xiaomi",
|
||||
"e8:51:77": "Hisense/Qingdao",
|
||||
"48:9e:9d": "тв Родители кабинет",
|
||||
"c4:8b:66": "Chromecast Гостиная",
|
||||
"14:ea:63": "Chromecast Smart TV Pro",
|
||||
"d4:f7:d5": "PlayStation 5",
|
||||
"50:8b:b9": "Tuya",
|
||||
}
|
||||
|
||||
print(f" аренд всего: {len(hosts)}")
|
||||
for h in hosts:
|
||||
mac = (h.get("mac") or "").lower()
|
||||
for pref, label in TARGETS.items():
|
||||
if mac.startswith(pref):
|
||||
print(f" {str(h.get('ip') or h.get('address')):<16} {mac:<18} {label} "
|
||||
f"| имя: {(h.get('name') or '—')[:40]}")
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Опрашивает остальные роутеры Keenetic тем же логином."""
|
||||
import hashlib
|
||||
import http.cookiejar
|
||||
import json
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
CREDS = json.load(open("/root/.keenetic.json", encoding="utf-8"))
|
||||
LOGIN, PASSWORD = CREDS["login"], CREDS["password"]
|
||||
|
||||
|
||||
def session(base):
|
||||
jar = http.cookiejar.CookieJar()
|
||||
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
try:
|
||||
r = op.open(urllib.request.Request(base + "/auth"), timeout=8)
|
||||
ch, realm = r.headers.get("X-NDM-Challenge"), r.headers.get("X-NDM-Realm")
|
||||
except urllib.error.HTTPError as e:
|
||||
ch, realm = e.headers.get("X-NDM-Challenge"), e.headers.get("X-NDM-Realm")
|
||||
except Exception as e:
|
||||
return None, str(e)[:60]
|
||||
if not ch:
|
||||
return None, "нет challenge"
|
||||
md5 = hashlib.md5(f"{LOGIN}:{realm}:{PASSWORD}".encode()).hexdigest()
|
||||
sha = hashlib.sha256((ch + md5).encode()).hexdigest()
|
||||
body = json.dumps({"login": LOGIN, "password": sha}).encode()
|
||||
try:
|
||||
op.open(urllib.request.Request(base + "/auth", data=body, method="POST",
|
||||
headers={"Content-Type": "application/json"}), timeout=8)
|
||||
except Exception as e:
|
||||
return None, str(e)[:60]
|
||||
return op, None
|
||||
|
||||
|
||||
def get(op, base, path):
|
||||
try:
|
||||
with op.open(urllib.request.Request(base + path), timeout=15) as r:
|
||||
raw = r.read()
|
||||
return (json.loads(raw) if raw else {}), None
|
||||
except Exception as e:
|
||||
return None, str(e)[:80]
|
||||
|
||||
|
||||
for base in ("http://192.168.1.63", "http://192.168.1.3"):
|
||||
print(f"=== {base} ===")
|
||||
op, err = session(base)
|
||||
if err:
|
||||
print(" вход:", err)
|
||||
continue
|
||||
v, _ = get(op, base, "/rci/show/version")
|
||||
print(" модель:", (v or {}).get("device"), "| версия:", (v or {}).get("release"))
|
||||
live, err = get(op, base, "/rci/show/ip/hotspot")
|
||||
hosts = (live or {}).get("host") or []
|
||||
if isinstance(hosts, dict):
|
||||
hosts = list(hosts.values())
|
||||
print(" клиентов:", len(hosts))
|
||||
for h in hosts:
|
||||
name = (h.get("name") or h.get("hostname") or "—").split(" - Home network")[0]
|
||||
print(f" {str(h.get('ip')):<16} {h.get('mac','—'):<18} {name[:45]}")
|
||||
Reference in new issue
Block a user