147 lines
5.4 KiB
Python
Executable File
147 lines
5.4 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Проверка каналов доступа: Reality 443, WS 8445, XHTTP 8444, Cloudflare.
|
|
|
|
Пишет /var/lib/vpn-health/<дата>.jsonl, при деградации шлёт уведомление
|
|
в /notify (один раз на переход состояния, без спама).
|
|
|
|
Запуск: systemd-таймер каждые 10 минут.
|
|
"""
|
|
import json
|
|
import os
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
|
|
VDS = "193.233.210.184"
|
|
SNI = "git.buryans.ru"
|
|
OUT = "/var/lib/vpn-health"
|
|
STATE = "/var/lib/vpn-health/last.json"
|
|
CF_LOG = "/var/log/cf-tunnel.log"
|
|
|
|
|
|
def tls(port, timeout=8):
|
|
t0 = time.time()
|
|
ctx = ssl.create_default_context()
|
|
ctx.check_hostname = False
|
|
ctx.verify_mode = ssl.CERT_NONE
|
|
try:
|
|
with socket.create_connection((VDS, port), timeout=timeout) as raw:
|
|
with ctx.wrap_socket(raw, server_hostname=SNI) as ss:
|
|
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1),
|
|
"tls": ss.version()}
|
|
except Exception as e:
|
|
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
|
"err": type(e).__name__}
|
|
|
|
|
|
CF_FILE = "/root/buryan-infra/ops/vpn/cf-host.txt"
|
|
|
|
|
|
def cf_host():
|
|
try:
|
|
h = open(CF_FILE, encoding="utf-8").read().strip()
|
|
if h.startswith("https://"):
|
|
return h
|
|
except Exception:
|
|
pass
|
|
try:
|
|
for line in reversed(open(CF_LOG, encoding="utf-8", errors="replace").read().splitlines()):
|
|
if "trycloudflare.com" in line:
|
|
for tok in line.split():
|
|
if tok.startswith("https://") and "trycloudflare.com" in tok:
|
|
return tok.strip()
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
|
|
def http(url, timeout=12):
|
|
t0 = time.time()
|
|
try:
|
|
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
|
|
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
return {"ok": True, "ms": round((time.time() - t0) * 1000, 1),
|
|
"code": r.status}
|
|
except urllib.error.HTTPError as e:
|
|
# 404/400 от xray — это норма (ждёт WebSocket), значит канал живой
|
|
return {"ok": e.code in (400, 404), "ms": round((time.time() - t0) * 1000, 1),
|
|
"code": e.code}
|
|
except Exception as e:
|
|
return {"ok": False, "ms": round((time.time() - t0) * 1000, 1),
|
|
"err": type(e).__name__}
|
|
|
|
|
|
def notify(title, message, priority="high"):
|
|
try:
|
|
body = json.dumps({"title": title, "message": message,
|
|
"priority": priority}).encode()
|
|
req = urllib.request.Request("http://127.0.0.1:9120/notify", data=body,
|
|
headers={"Content-Type": "application/json"})
|
|
urllib.request.urlopen(req, timeout=10).read()
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
def main():
|
|
rec = {"ts": time.strftime("%Y-%m-%dT%H:%M:%S")}
|
|
rec["reality443"] = tls(443)
|
|
rec["ws8445"] = tls(8445)
|
|
rec["xhttp8444"] = tls(8444)
|
|
cf = cf_host()
|
|
rec["cf_host"] = cf
|
|
rec["cf"] = http(cf + "/") if cf else {"ok": False, "err": "no_host"}
|
|
|
|
os.makedirs(OUT, exist_ok=True)
|
|
with open(os.path.join(OUT, time.strftime("%Y-%m-%d") + ".jsonl"), "a",
|
|
encoding="utf-8") as f:
|
|
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
|
|
|
# состояние: сравниваем с прошлым замером
|
|
prev = {}
|
|
try:
|
|
prev = json.load(open(STATE, encoding="utf-8"))
|
|
except Exception:
|
|
pass
|
|
open(STATE, "w", encoding="utf-8").write(json.dumps(rec, ensure_ascii=False))
|
|
|
|
names = {"reality443": "Reality 443", "ws8445": "WS 8445",
|
|
"xhttp8444": "XHTTP 8444", "cf": "Cloudflare"}
|
|
|
|
# Антиспам: волны длятся секунды-минуты и приходят каждые 10-20 минут.
|
|
# Алерт — только если канал лежит ДВЕ проверки подряд (20 минут),
|
|
# восстановление — только если по нему был алерт, и тихо (priority low).
|
|
dead_now = {k for k in names if not rec[k]["ok"]}
|
|
prev_streak = {k for k in (prev.get("dead_streak") or []) if k in names}
|
|
alerted = {k for k in (prev.get("alerted") or []) if k in names}
|
|
|
|
streak = (dead_now & prev_streak) | dead_now # текущая серия
|
|
newly_down = {k for k in dead_now if k in prev_streak} - alerted
|
|
recovered = alerted - dead_now
|
|
|
|
if newly_down:
|
|
alive = [names[k] for k in names if k not in dead_now]
|
|
notify("VPN: канал недоступен 20+ минут",
|
|
"Не работают: %s.\nРаботают: %s.\nПроверьте профиль в клиенте."
|
|
% (", ".join(names[k] for k in sorted(newly_down)),
|
|
", ".join(alive) or "нет"))
|
|
alerted |= newly_down
|
|
|
|
if recovered and not dead_now:
|
|
notify("VPN: каналы восстановлены",
|
|
"Все каналы отвечают: Reality 443, WS 8445, XHTTP 8444, Cloudflare.",
|
|
priority="low")
|
|
alerted = set()
|
|
|
|
rec["dead_streak"] = sorted(streak)
|
|
rec["alerted"] = sorted(alerted)
|
|
|
|
print(rec["ts"], "ok" if not dead_now else "СБОЙ: " + ",".join(dead_now),
|
|
"| CF:", cf or "нет")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|