Files
buryan-infra/ops/network/keenetic.py
T
buryan-agent 2c86d3d0e4 Инвентаризация через 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 недоступен.
2026-10-20 15:30:38 +03:00

217 lines
7.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Инвентаризация 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())