#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Add domestic Tencent WireGuard hub (wg-dy-cn) alongside overseas wg-dy. Topology (coexist): 10.9.0.1 Domestic hub 82.157.112.245:51821 10.9.0.2 Physical app (primary peer — low CN latency) 10.9.0.3 Overseas VPS (Caddy edge reaches app via 10.9.0.2) Keeps existing wg-dy (10.8.0.0/24) on overseas + physical as backup. Updates dy.nomadro.com Caddy + NEKO DNAT to prefer 10.9.0.2. """ from __future__ import annotations import sys import time import paramiko if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") OVERSEAS = "107.173.30.245" DOMESTIC = "82.157.112.245" DOMESTIC_USER = "ubuntu" DOMESTIC_PASS = "Xiao4669805" OVERSEAS_PASS = "Xiao4669805" GUEST_USER = "eric" GUEST_PASS = "4669805" CN_PORT = 51821 CN_NET = "10.9.0" PHYSICAL_CN = f"{CN_NET}.2" OVERSEAS_CN = f"{CN_NET}.3" DOMESTIC_CN = f"{CN_NET}.1" PHYSICAL_LEGACY = "10.8.0.2" def ssh(host, port, user, pw, tries=6): last = None for i in range(tries): try: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(host, port, user, pw, timeout=45, banner_timeout=90, allow_agent=False, look_for_keys=False) return c except Exception as ex: last = ex print(f"ssh {host}:{port} try{i} {type(ex).__name__}", flush=True) time.sleep(2 + i) raise last # type: ignore[misc] def run(c, cmd, timeout=180): _, o, e = c.exec_command(cmd, timeout=timeout) return (o.read() + e.read()).decode("utf-8", "replace") def must_dylive(v): code = run(v, "curl -sS -m 8 -o /dev/null -w '%{http_code}' https://dylive.nomadro.com/api/health", 20).strip() print(f"[dylive] {code}", flush=True) if code != "200": raise SystemExit(f"ABORT dylive health {code}") def write_remote(sftp, path, content, mode=0o600): with sftp.file(path, "w") as f: f.write(content) sftp.chmod(path, mode) def main() -> int: v = ssh(OVERSEAS, 22, "root", OVERSEAS_PASS) must_dylive(v) print("=== generate wg-dy-cn keys on domestic hub ===", flush=True) d = ssh(DOMESTIC, 22, DOMESTIC_USER, DOMESTIC_PASS) key_out = run( d, f"sudo bash -c '" f"export DEBIAN_FRONTEND=noninteractive; " f"apt-get install -y --no-install-recommends wireguard-tools >/tmp/wg-cn-apt.log 2>&1; " f"mkdir -p /etc/wireguard && chmod 700 /etc/wireguard; " f"if [ ! -f /etc/wireguard/wg-dy-cn.hub.key ]; then " f" wg genkey | tee /etc/wireguard/wg-dy-cn.hub.key | wg pubkey > /etc/wireguard/wg-dy-cn.hub.pub; " f" wg genkey | tee /etc/wireguard/wg-dy-cn.pve.key | wg pubkey > /etc/wireguard/wg-dy-cn.pve.pub; " f" wg genkey | tee /etc/wireguard/wg-dy-cn.vps.key | wg pubkey > /etc/wireguard/wg-dy-cn.vps.pub; " f" chmod 600 /etc/wireguard/wg-dy-cn.*.key; " f"fi; " f"echo HUB_PRIV $(cat /etc/wireguard/wg-dy-cn.hub.key); " f"echo HUB_PUB $(cat /etc/wireguard/wg-dy-cn.hub.pub); " f"echo PVE_PRIV $(cat /etc/wireguard/wg-dy-cn.pve.key); " f"echo PVE_PUB $(cat /etc/wireguard/wg-dy-cn.pve.pub); " f"echo VPS_PRIV $(cat /etc/wireguard/wg-dy-cn.vps.key); " f"echo VPS_PUB $(cat /etc/wireguard/wg-dy-cn.vps.pub)'", 240, ) print(key_out, flush=True) kv: dict[str, str] = {} for line in key_out.splitlines(): parts = line.split() if len(parts) == 2 and parts[0] in ("HUB_PRIV", "HUB_PUB", "PVE_PRIV", "PVE_PUB", "VPS_PRIV", "VPS_PUB"): kv[parts[0]] = parts[1] if len(kv) != 6: raise SystemExit("key generation failed") hub_conf = f"""[Interface] Address = {DOMESTIC_CN}/24 ListenPort = {CN_PORT} PrivateKey = {kv['HUB_PRIV']} [Peer] # Physical app host (primary) PublicKey = {kv['PVE_PUB']} AllowedIPs = {PHYSICAL_CN}/32 [Peer] # Overseas edge VPS (backup path coexists with wg-dy) PublicKey = {kv['VPS_PUB']} AllowedIPs = {OVERSEAS_CN}/32 """ pve_conf = f"""[Interface] Address = {PHYSICAL_CN}/24 PrivateKey = {kv['PVE_PRIV']} [Peer] PublicKey = {kv['HUB_PUB']} Endpoint = {DOMESTIC}:{CN_PORT} AllowedIPs = {CN_NET}.0/24 PersistentKeepalive = 25 """ vps_conf = f"""[Interface] Address = {OVERSEAS_CN}/24 PrivateKey = {kv['VPS_PRIV']} [Peer] PublicKey = {kv['HUB_PUB']} Endpoint = {DOMESTIC}:{CN_PORT} AllowedIPs = {CN_NET}.0/24 PersistentKeepalive = 25 """ print("=== write hub config on domestic ===", flush=True) dsftp = d.open_sftp() write_remote(dsftp, "/tmp/wg-dy-cn.conf", hub_conf) dsftp.close() print( run( d, "sudo mv /tmp/wg-dy-cn.conf /etc/wireguard/wg-dy-cn.conf && " "sudo chmod 600 /etc/wireguard/wg-dy-cn.conf && " "sudo sysctl -w net.ipv4.ip_forward=1 && " "(sudo ufw allow 51821/udp || true) && " "sudo wg-quick down wg-dy-cn 2>/dev/null || true; " "sudo wg-quick up wg-dy-cn; " "sudo systemctl enable wg-quick@wg-dy-cn; " "sudo wg show wg-dy-cn; ip -4 addr show wg-dy-cn", 60, ), flush=True, ) print("=== write wg-dy-cn on overseas VPS ===", flush=True) vsftp = v.open_sftp() write_remote(vsftp, "/etc/wireguard/wg-dy-cn.conf", vps_conf) vsftp.close() print( run( v, "wg-quick down wg-dy-cn 2>/dev/null || true; " "wg-quick up wg-dy-cn; " "systemctl enable wg-quick@wg-dy-cn; " "wg show wg-dy-cn; ip -4 addr show wg-dy-cn", 45, ), flush=True, ) must_dylive(v) print("=== write wg-dy-cn on physical guest ===", flush=True) g = ssh(OVERSEAS, 4014, GUEST_USER, GUEST_PASS) gsftp = g.open_sftp() write_remote(gsftp, "/tmp/wg-dy-cn.conf", pve_conf) gsftp.close() print( run( g, f"echo '{GUEST_PASS}' | sudo -S -p '' bash -c '" f"export DEBIAN_FRONTEND=noninteractive; " f"apt-get install -y --no-install-recommends wireguard-tools >/tmp/wg-cn-apt.log 2>&1 || true; " f"mv /tmp/wg-dy-cn.conf /etc/wireguard/wg-dy-cn.conf; " f"chmod 600 /etc/wireguard/wg-dy-cn.conf; " f"wg-quick down wg-dy-cn 2>/dev/null || true; " f"wg-quick up wg-dy-cn; " f"systemctl enable wg-quick@wg-dy-cn; " f"wg show wg-dy-cn; ip -4 addr show wg-dy-cn; " f"ping -c 3 -W 2 {DOMESTIC_CN} | tail -3; " f"ping -c 3 -W 2 {OVERSEAS_CN} | tail -3'", 120, ), flush=True, ) print("=== update wireguard-watch to prefer wg-dy-cn ===", flush=True) print( run( g, f"echo '{GUEST_PASS}' | sudo -S -p '' bash -c '" f"mkdir -p /etc/systemd/system/douyinweb-wireguard-watch.service.d; " f"cat >/etc/systemd/system/douyinweb-wireguard-watch.service.d/wg-cn.conf </dev/null || true; " f"grep DY_NEKO_EDGE /etc/systemd/system/douyinweb-api.service 2>/dev/null || true'", 60, ), flush=True, ) print("=== update physical DY_NEKO_EDGE_UPSTREAM ===", flush=True) print( run( g, f"echo '{GUEST_PASS}' | sudo -S -p '' bash -c '" f"if grep -q DY_NEKO_EDGE_UPSTREAM= /etc/systemd/system/douyinweb-api.service; then " f" sed -i \"s/DY_NEKO_EDGE_UPSTREAM=.*/Environment=DY_NEKO_EDGE_UPSTREAM={PHYSICAL_CN}/\" /etc/systemd/system/douyinweb-api.service; " f"else " f" sed -i \"/\\[Service\\]/a Environment=DY_NEKO_EDGE_UPSTREAM={PHYSICAL_CN}\" /etc/systemd/system/douyinweb-api.service; " f"fi; " f"systemctl daemon-reload; " f"systemctl restart douyinweb-api; sleep 3; systemctl is-active douyinweb-api'", 90, ), flush=True, ) g.close() print("=== preflight wg-dy-cn (skip Caddy switch if unhealthy) ===", flush=True) pre = run( v, f"wg show wg-dy-cn; ping -c 2 -W 3 {PHYSICAL_CN} | tail -3; " f"curl -sS -m 8 -o /dev/null -w 'api_cn=%{{http_code}}\\n' http://{PHYSICAL_CN}:8014/api/health || true", 30, ) print(pre, flush=True) cn_ok = "api_cn=200" in pre and "1 received" in pre if not cn_ok: print( "WARN: wg-dy-cn not ready — open Tencent SG inbound UDP 51821, then run scripts/_activate_wg_cn_primary.py", flush=True, ) v.close() d.close() print("DONE — wg-dy-cn configured (standby); wg-dy remains active", flush=True) return 0 print("=== switch Caddy dy.nomadro.com to 10.9.0.2 (keep wg-dy backup manually) ===", flush=True) caddy_site = "/etc/caddy/sites/dy.nomadro.com.caddy" print( run( v, f"cp -a {caddy_site} {caddy_site}.bak-wg-cn-$(date +%Y%m%d%H%M) && " f"sed -i 's/{PHYSICAL_LEGACY}/{PHYSICAL_CN}/g' {caddy_site} && " f"grep -E '10\\.9\\.0\\.|10\\.8\\.0\\.' {caddy_site} | head -20 && " f"caddy validate --config /etc/caddy/Caddyfile && systemctl reload caddy", 60, ), flush=True, ) must_dylive(v) print("=== update NEKO WebRTC DNAT via wg-dy-cn → 10.9.0.2 ===", flush=True) v.close() d.close() import subprocess r = subprocess.run([sys.executable, str(__import__("pathlib").Path(__file__).resolve().parent / "_fix_neko_webrtc_forward.py")], capture_output=True, text=True) print(r.stdout, flush=True) if r.stderr.strip(): print(r.stderr, flush=True) if r.returncode != 0: print(f"WARN: neko forward exit {r.returncode}", flush=True) v = ssh(OVERSEAS, 22, "root", OVERSEAS_PASS) print("=== latency compare ===", flush=True) print( run( v, f"echo 'legacy wg-dy:'; ping -c 3 -W 2 {PHYSICAL_LEGACY} | tail -2; " f"echo 'primary wg-dy-cn:'; ping -c 3 -W 2 {PHYSICAL_CN} | tail -2; " f"curl -sS -m 10 -o /dev/null -w 'api_legacy=%{{http_code}} t=%{{time_total}}s\\n' http://{PHYSICAL_LEGACY}:8014/api/health; " f"curl -sS -m 10 -o /dev/null -w 'api_cn=%{{http_code}} t=%{{time_total}}s\\n' http://{PHYSICAL_CN}:8014/api/health; " f"curl -sS -m 10 -o /dev/null -w 'dy=%{{http_code}} t=%{{time_total}}s\\n' https://dy.nomadro.com/api/health; " f"curl -sS -m 10 -o /dev/null -w 'neko=%{{http_code}} t=%{{time_total}}s\\n' https://dy.nomadro.com/neko/1/", 60, ), flush=True, ) print("=== final wg status ===", flush=True) print(run(v, "wg show wg-dy; echo ---; wg show wg-dy-cn", 20), flush=True) d = ssh(DOMESTIC, 22, DOMESTIC_USER, DOMESTIC_PASS) print(run(d, "sudo wg show wg-dy-cn", 20), flush=True) v.close() d.close() print("DONE — wg-dy-cn primary, wg-dy backup coexist", flush=True) return 0 if __name__ == "__main__": raise SystemExit(main())