Files
buryan-infra/ops/scripts/cf_tunnel_sync.py
T

186 lines
6.4 KiB
Python
Executable File
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.
#!/usr/bin/env python3
"""Синхронизация быстрого Cloudflare-туннеля (URL меняется при перезапуске).
Что делает за один прогон:
1. читает текущий URL туннеля с VDS через WireGuard (10.88.0.1);
2. сравнивает с ops/vpn/cf-host.txt;
3. при смене — обновляет cf-host.txt и клиентские профили:
добавляет/обновляет отк��ут proxy-cf (VLESS+WS+TLS к *.trycloudflare.com),
включает его в observatory и balancer — переключение автоматическое;
4. проверяет туннель снаружи (path /buryan-cf должен отвечать 400);
5. при изменениях уведомляет в ALERT.
Запуск: python3 cf_tunnel_sync.py [--dry-run]
Hermes: cf-tunnel-sync каждые 5 минут.
"""
import glob
import json
import os
import re
import shutil
import subprocess
import sys
import time
REPO = "/root/buryan-infra"
CF_HOST_FILE = REPO + "/ops/vpn/cf-host.txt"
PROFILES = REPO + "/ops/vpn/build/profiles/vpn-*.json"
STATE = "/var/lib/cf-tunnel/last-url"
UUID_FILE = "/root/.cf-uuid"
VDS = "10.88.0.1"
PATH = "/buryan-cf"
def sh(cmd, timeout=40):
r = subprocess.run(cmd, shell=True, capture_output=True, text=True, timeout=timeout)
return ((r.stdout or "") + (r.stderr or "")).strip()
def vds(cmd):
return sh("ssh -o BatchMode=yes -o ConnectTimeout=8 root@%s '%s'" % (VDS, cmd.replace("'", "'\\''")), timeout=45)
def get_url():
out = vds("journalctl -u cf-tunnel -n 400 --no-pager 2>/dev/null | "
"grep -oE 'https://[a-z0-9-]+\\.trycloudflare\\.com' | tail -1")
m = re.search(r"https://[a-z0-9-]+\.trycloudflare\.com", out)
return m.group(0) if m else ""
def get_uuid():
try:
u = open(UUID_FILE, encoding="utf-8").read().strip()
if re.match(r"^[0-9a-f-]{36}$", u):
return u
except Exception:
pass
out = vds("python3 /root/cf-uuid.py")
m = re.search(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", out)
if m:
try:
open(UUID_FILE, "w", encoding="utf-8").write(m.group(0))
os.chmod(UUID_FILE, 0o600)
except Exception:
pass
return m.group(0)
return ""
def make_outbound(host, uuid):
return {
"tag": "proxy-cf",
"protocol": "vless",
"settings": {"vnext": [{"address": host, "port": 443,
"users": [{"id": uuid, "encryption": "none"}]}]},
"streamSettings": {
"network": "ws",
"security": "tls",
"tlsSettings": {"serverName": host, "fingerprint": "firefox",
"allowInsecure": False},
"wsSettings": {"path": PATH},
},
}
def update_profile(path, host, uuid, dry=False):
d = json.load(open(path, encoding="utf-8"))
ob = next((o for o in d.get("outbounds", []) if o.get("tag") == "proxy-cf"), None)
changed = False
if ob is None:
new = make_outbound(host, uuid)
outs = d.get("outbounds", [])
idx = next((i for i, o in enumerate(outs) if o.get("tag") == "direct"), len(outs))
outs.insert(idx, new)
d["outbounds"] = outs
changed = True
else:
vn = (ob.get("settings") or {}).get("vnext") or [{}]
if vn[0].get("address") != host:
vn[0]["address"] = host
changed = True
tls = (ob.get("streamSettings") or {}).get("tlsSettings") or {}
if tls.get("serverName") != host:
tls["serverName"] = host
ob["streamSettings"]["tlsSettings"] = tls
changed = True
obs = d.setdefault("observatory", {})
sel = obs.setdefault("subjectSelector", [])
if "proxy-cf" not in sel:
sel.append("proxy-cf")
changed = True
for b in (d.get("routing") or {}).get("balancers") or []:
s = b.setdefault("selector", [])
if "proxy-cf" not in s:
s.append("proxy-cf")
changed = True
if changed and not dry:
shutil.copy2(path, path + ".bak-cf")
json.dump(d, open(path, "w", encoding="utf-8"), ensure_ascii=False, indent=1)
return changed
def notify(title, text, priority="high"):
try:
subprocess.run(["/usr/bin/python3", "/opt/buryan-hub/scripts/notify.py",
"--priority", priority, "--title", title, text],
capture_output=True, text=True, timeout=120)
except Exception:
pass
def main():
dry = "--dry-run" in sys.argv
url = get_url()
if not url:
notify("CF-туннель", "Не удалось получить URL туннеля с VDS (WG).", "high")
print("URL не получен")
return 1
host = url.replace("https://", "")
try:
old = open(CF_HOST_FILE, encoding="utf-8").read().strip()
except Exception:
old = ""
changed_url = old != url
uuid = get_uuid()
print("URL:", url, "| изменился:", changed_url, "| uuid:", "есть" if uuid else "НЕТ")
if changed_url and not dry:
open(CF_HOST_FILE, "w", encoding="utf-8").write(url + "\n")
touched = []
if uuid:
for p in sorted(glob.glob(PROFILES)):
try:
if update_profile(p, host, uuid, dry):
touched.append(os.path.basename(p))
except Exception as e:
print(" ошибка профиля", p, e)
print("профилей обновлено:", len(touched), touched[:6])
# проверка снаружи: /buryan-cf без WebSocket → 400
code = sh("curl -s -o /dev/null -w '%%{http_code}' -m 12 '%s%s'" % (url, PATH), timeout=20)
print("туннель /buryan-cf:", code)
healthy = code in ("400", "426")
if changed_url and not dry:
try:
os.makedirs(os.path.dirname(STATE), exist_ok=True)
open(STATE, "w", encoding="utf-8").write(url)
except Exception:
pass
if touched:
notify("CF-туннель: новый адрес",
"URL: %s\nПрофилей обновлено: %d\nПроверка: %s"
% (url, len(touched), code))
if not healthy:
notify("CF-туннель не отвечает", "URL: %s, код: %s" % (url, code), "high")
return 1
return 0
if __name__ == "__main__":
sys.exit(main())