#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Find an open UDP port on domestic Tencent SG and rebind wg-dy-cn.""" from __future__ import annotations import re import sys import time import paramiko if hasattr(sys.stdout, "reconfigure"): sys.stdout.reconfigure(encoding="utf-8", errors="replace") DOMESTIC = ("82.157.112.245", 22, "ubuntu", "Xiao4669805") OVERSEAS = ("107.173.30.245", 22, "root", "Xiao4669805") GUEST = ("107.173.30.245", 4014, "eric", "4669805") CANDIDATE_PORTS = (51820, 7000, 4000, 51821, 51822) def ssh(t): c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(t[0], t[1], t[2], t[3], timeout=45, allow_agent=False, look_for_keys=False) return c def run(c, cmd, timeout=90): _, o, e = c.exec_command(cmd, timeout=timeout) return (o.read() + e.read()).decode("utf-8", "replace") def probe_port(port: int) -> bool: d = ssh(DOMESTIC) d.exec_command(f"sudo timeout 6 tcpdump -ni any udp port {port} -c 1 -q >/tmp/probe-{port}.log 2>&1 &", timeout=3) time.sleep(0.5) v = ssh(OVERSEAS) run(v, f"echo probe | nc -u -w1 82.157.112.245 {port} || true", 10) v.close() time.sleep(2) out = run(d, f"cat /tmp/probe-{port}.log 2>/dev/null", 10) d.close() ok = "1 packet captured" in out or "packets captured" in out and "0 packets" not in out print(f"port {port}: {'OPEN' if ok else 'blocked'} — {out.strip()[:120]}", flush=True) return ok def rebind_port(port: int) -> None: d = ssh(DOMESTIC) conf = run(d, "sudo cat /etc/wireguard/wg-dy-cn.conf", 15) conf = re.sub(r"ListenPort = \d+", f"ListenPort = {port}", conf) dsftp = d.open_sftp() with dsftp.file("/tmp/wg-dy-cn.conf", "w") as f: f.write(conf) dsftp.close() print(run(d, f"sudo mv /tmp/wg-dy-cn.conf /etc/wireguard/wg-dy-cn.conf && sudo wg-quick down wg-dy-cn; sudo wg-quick up wg-dy-cn; sudo wg show wg-dy-cn", 30)) d.close() endpoint = f"82.157.112.245:{port}" for label, t in (("vps", OVERSEAS), ("pve", GUEST)): c = ssh(t) if label == "pve": cmd = ( f"echo '4669805' | sudo -S -p '' bash -c '" f"conf=/etc/wireguard/wg-dy-cn.conf; " f"sed -i \"s|Endpoint = .*|Endpoint = {endpoint}|\" $conf; " f"wg-quick down wg-dy-cn; wg-quick up wg-dy-cn; wg show wg-dy-cn'" ) else: cmd = f"conf=/etc/wireguard/wg-dy-cn.conf; sed -i 's|Endpoint = .*|Endpoint = {endpoint}|' $conf; wg-quick down wg-dy-cn; wg-quick up wg-dy-cn; wg show wg-dy-cn" print(f"=== {label} ===\n{run(c, cmd, 30)}", flush=True) c.close() time.sleep(2) v = ssh(OVERSEAS) print(run(v, "ping -c 3 -W 2 10.9.0.2 | tail -3; wg show wg-dy-cn", 30)) v.close() d = ssh(DOMESTIC) print(run(d, "sudo wg show wg-dy-cn", 15)) d.close() def main(): open_port = None for p in CANDIDATE_PORTS: if probe_port(p): open_port = p break if not open_port: print("No UDP port reachable — open UDP 51821 (or 51820) in Tencent security group for 82.157.112.245", flush=True) return 1 print(f"Using port {open_port}", flush=True) rebind_port(open_port) return 0 if __name__ == "__main__": raise SystemExit(main())