130 lines
4.6 KiB
Python
Executable File
130 lines
4.6 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):
|
|
try:
|
|
body = json.dumps({"title": title, "message": message,
|
|
"priority": "high"}).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"}
|
|
dead_now = [names[k] for k in names if not rec[k]["ok"]]
|
|
dead_prev = [names[k] for k in names if prev.get(k) and not prev[k].get("ok")]
|
|
|
|
if dead_now and dead_now != dead_prev:
|
|
alive = [names[k] for k in names if rec[k]["ok"]]
|
|
notify("VPN: канал недоступен",
|
|
"Не работают: %s.\nРаботают: %s.\nПроверьте профиль в клиенте."
|
|
% (", ".join(dead_now), ", ".join(alive) or "нет"))
|
|
elif not dead_now and dead_prev:
|
|
notify("VPN: каналы восстановлены",
|
|
"Все каналы отвечают: Reality 443, WS 8445, XHTTP 8444, Cloudflare.")
|
|
|
|
print(rec["ts"], "ok" if not dead_now else "СБОЙ: " + ",".join(dead_now),
|
|
"| CF:", cf or "нет")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main())
|