120 lines
4.3 KiB
Python
Executable File
120 lines
4.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Монитор качества связи: пишет замеры раз в минуту, чтобы поймать сбои за дни.
|
|
|
|
Зачем: сбои «то есть, то нет» нельзя поймать разовым тестом. Нужна история:
|
|
когда именно рвётся и на каком участке — Wi-Fi, роутер, провайдер или VPS.
|
|
|
|
Пишет JSONL: /var/lib/net-monitor/<дата>.jsonl
|
|
Ничего не меняет в сети: только ping, TCP-connect и TLS-хендшейк.
|
|
"""
|
|
import json
|
|
import os
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import time
|
|
|
|
OUT = "/var/lib/net-monitor"
|
|
VPS = "193.233.210.184"
|
|
SNI = "git.buryans.ru"
|
|
GATEWAY = "192.168.1.1"
|
|
INTERVAL = 60 # секунд между замерами
|
|
TLS_EVERY = 1 # TLS-проверка раз в N замеров
|
|
|
|
|
|
def ping(host, count=5):
|
|
try:
|
|
r = subprocess.run(["ping", "-c", str(count), "-i", "0.2", "-W", "1", host],
|
|
capture_output=True, text=True, timeout=count + 8)
|
|
out = r.stdout or ""
|
|
loss = 100.0
|
|
avg = None
|
|
for line in out.splitlines():
|
|
if "packet loss" in line:
|
|
try:
|
|
loss = float(line.split("%")[0].split()[-1])
|
|
except Exception:
|
|
pass
|
|
if "rtt min/avg/max" in line:
|
|
try:
|
|
avg = float(line.split("=")[1].split("/")[1])
|
|
except Exception:
|
|
pass
|
|
return {"loss": loss, "avg_ms": avg}
|
|
except Exception:
|
|
return {"loss": 100.0, "avg_ms": None}
|
|
|
|
|
|
def tcp(host, port, timeout=5):
|
|
t0 = time.time()
|
|
try:
|
|
s = socket.create_connection((host, port), timeout=timeout)
|
|
s.close()
|
|
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1)}
|
|
except Exception as e:
|
|
return {"ok": False, "ms": None, "err": type(e).__name__}
|
|
|
|
|
|
def tls(host, sni, timeout=8, port=443):
|
|
t0 = time.time()
|
|
ctx = ssl.create_default_context()
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
try:
|
|
with socket.create_connection((host, port), timeout=timeout) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname=sni) as ss:
|
|
ver = ss.version()
|
|
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1), "tls": ver}
|
|
except Exception as e:
|
|
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
|
"err": type(e).__name__}
|
|
|
|
|
|
def dns(name="matrix.buryans.ru"):
|
|
t0 = time.time()
|
|
try:
|
|
socket.gethostbyname(name)
|
|
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1)}
|
|
except Exception as e:
|
|
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
|
"err": type(e).__name__}
|
|
|
|
|
|
def main():
|
|
os.makedirs(OUT, exist_ok=True)
|
|
n = 0
|
|
while True:
|
|
n += 1
|
|
rec = {
|
|
"ts": time.strftime("%Y-%m-%dT%H:%M:%S"),
|
|
"gw": ping(GATEWAY),
|
|
"dns": dns(),
|
|
"vps_tcp": tcp(VPS, 443),
|
|
}
|
|
if n % TLS_EVERY == 0:
|
|
rec["vps_tls"] = tls(VPS, SNI)
|
|
# контроль: обычный зарубежный сайт. Если в момент волны он жив,
|
|
# а наш VDS мёртв — фильтруют конкретно наш адрес.
|
|
rec["control_tls"] = tls("www.microsoft.com", "www.microsoft.com")
|
|
# сравнение каналов: WS на 8445 и (если известен) Cloudflare
|
|
rec["ws_tls"] = tls(VPS, SNI, port=8445)
|
|
rec["net_tcp"] = tcp("ya.ru", 443)
|
|
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")
|
|
|
|
bad = []
|
|
if rec["gw"]["loss"] > 0:
|
|
bad.append("шлюз %.0f%% потерь" % rec["gw"]["loss"])
|
|
if not rec["vps_tcp"]["ok"]:
|
|
bad.append("VPS TCP сбой")
|
|
if rec.get("vps_tls") and not rec["vps_tls"]["ok"]:
|
|
bad.append("VPS TLS сбой")
|
|
if bad:
|
|
print("%s !!! %s" % (rec["ts"], ", ".join(bad)), flush=True)
|
|
time.sleep(INTERVAL)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|