#!/usr/bin/env python3 """Сбор статистики Wi-Fi с Keenetic по SSH раз в 2 минуты (только чтение). Пишет JSONL: /var/lib/router-monitor/<дата>.jsonl Зачем: увидеть за дни, деградирует ли сигнал, меняются ли каналы, сколько клиентов и на каких диапазонах, рвётся ли что-то. """ import json import os import re import subprocess import time OUT = "/var/lib/router-monitor" ROUTER = "192.168.1.1" CRED = "/root/.keenetic.json" INTERVAL = 120 def ssh(cmd, timeout=25): try: cred = json.load(open(CRED)) pwd = cred["password"] user = cred["username"] except Exception: pwd, user = "73145146", "admin" try: r = subprocess.run( ["sshpass", "-p", pwd, "ssh", "-o", "StrictHostKeyChecking=no", "-o", "UserKnownHostsFile=/dev/null", "-o", "ConnectTimeout=8", "-o", "PubkeyAuthentication=no", "-o", "LogLevel=ERROR", "%s@%s" % (user, ROUTER), cmd], capture_output=True, text=True, timeout=timeout) return re.sub(r"\x1b\[[0-9;]*[A-Za-z]", "", r.stdout or "") except Exception: return "" def parse_assoc(text): """Список клиентов: mac, ap, txrate, rxrate, rssi, band.""" out = [] cur = {} for line in text.splitlines(): s = line.strip() m = re.match(r"mac:\s*(\S+)", s) if m: if cur.get("mac"): out.append(cur) cur = {"mac": m.group(1)} continue m = re.match(r"ap:\s*(\S+)", s) if m: cur["ap"] = m.group(1) continue m = re.match(r"txrate:\s*(\d+)", s) if m: cur["tx"] = int(m.group(1)) continue m = re.match(r"rxrate:\s*(\d+)", s) if m: cur["rx"] = int(m.group(1)) continue m = re.match(r"rssi:\s*(-?\d+)", s) if m: cur["rssi"] = int(m.group(1)) if cur.get("mac"): out.append(cur) for c in out: c["band"] = "5" if "WifiMaster1" in str(c.get("ap", "")) else "2.4" return out def parse_radio(name): t = ssh("show interface %s" % name) d = {} m = re.search(r"channel:\s*(\d+)", t) if m: d["channel"] = int(m.group(1)) m = re.search(r"bandwidth:\s*(\d+)", t) if m: d["width"] = int(m.group(1)) d["busy"] = [int(x) for x in re.findall(r"busy-channels:\s*(\d+)", t)] return d def main(): os.makedirs(OUT, exist_ok=True) while True: rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S")} rec["wifi24"] = parse_radio("WifiMaster0") rec["wifi5"] = parse_radio("WifiMaster1") rec["clients"] = parse_assoc(ssh("show associations")) path = os.path.join(OUT, time.strftime("%Y-%m-%d") + ".jsonl") with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(rec, ensure_ascii=False) + "\n") n24 = sum(1 for c in rec["clients"] if c["band"] == "2.4") n5 = len(rec["clients"]) - n24 print("%s клиентов: 2.4=%d 5=%d | ch24=%s busy=%s" % (rec["ts"], n24, n5, rec["wifi24"].get("channel"), len(rec["wifi24"].get("busy") or [])), flush=True) time.sleep(INTERVAL) if __name__ == "__main__": main()