douyinWEB/scripts/_switch_neko_nat1to1_tencent.py
eric d409e416da Ship physical dual-edge stack, Studio CDP live metrics, and ops tooling.
Capture Neko/WG/network hubs, Studio viewer charts, physical deploy docs, and one-shot scripts so VPS vs physical can be toggled later without losing WIP.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-04 22:42:40 -05:00

191 lines
6.1 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Switch Neko WebRTC NAT1TO1 to Tencent (82.157.112.245) and recreate containers.
CN clients advertise ICE → Tencent → DNAT → 10.9.0.2.
Also probes whether Tencent SG allows WebRTC ports from the internet.
"""
from __future__ import annotations
import sys
import time
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
TENCENT_IP = "82.157.112.245"
GUEST_PASS = "4669805"
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=60,
banner_timeout=120,
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=600):
_, o, e = c.exec_command(cmd, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def main() -> int:
print("=== 1) probe Tencent SG reachability from overseas ===", flush=True)
v = ssh("107.173.30.245", 22, "root", "Xiao4669805")
# TCP connect probe to mux ports (UDP hard to probe; TCP mux is enough signal)
probe = run(
v,
f"""
for p in 52300 52301 80 443; do
timeout 3 bash -c 'echo >/dev/tcp/{TENCENT_IP}/'$p'' 2>/dev/null && echo TCP_$p=OPEN || echo TCP_$p=BLOCKED
done
# UDP send + check if anything comes back is unreliable; just send
for p in 52300 52000; do
echo probe | timeout 2 nc -u -w1 {TENCENT_IP} $p 2>/dev/null || true
echo UDP_sent_$p
done
""",
40,
)
print(probe, flush=True)
print("=== 2) physical: set NAT1TO1 + recreate neko ===", flush=True)
g = ssh("107.173.30.245", 4014, "eric", GUEST_PASS)
remote = f"""#!/bin/bash
set -euo pipefail
PASS='{GUEST_PASS}'
sudo_run() {{ echo "$PASS" | sudo -S -p '' bash -c "$1"; }}
SVC=/etc/systemd/system/douyinweb-api.service
sudo_run "sed -i '/DY_NEKO_NAT1TO1=/d' $SVC"
sudo_run "sed -i '/\\[Service\\]/a Environment=DY_NEKO_NAT1TO1={TENCENT_IP}' $SVC"
if [ -f /etc/douyinweb.env ]; then
sudo_run "grep -q ^DY_NEKO_NAT1TO1= /etc/douyinweb.env && sed -i 's|^DY_NEKO_NAT1TO1=.*|DY_NEKO_NAT1TO1={TENCENT_IP}|' /etc/douyinweb.env || echo DY_NEKO_NAT1TO1={TENCENT_IP} >> /etc/douyinweb.env"
fi
# clear cached IP so compose regeneration picks env
sudo_run "rm -f /opt/douyinWEB/backend/data/neko/nat1to1.txt /var/lib/douyinweb/neko/nat1to1.txt 2>/dev/null; find /opt/douyinWEB -name nat1to1.txt -delete 2>/dev/null || true"
sudo_run "systemctl daemon-reload; systemctl restart douyinweb-api"
sleep 4
systemctl is-active douyinweb-api
grep DY_NEKO_NAT1TO1 $SVC || true
# recreate via API helper inside venv
cd /opt/douyinWEB/backend
export DY_NEKO_NAT1TO1={TENCENT_IP}
export DY_PUBLIC_BASE_URL=https://dy.nomadro.com
.venv/bin/python <<'PY'
import os
os.environ["DY_NEKO_NAT1TO1"] = "{TENCENT_IP}"
from app import youtube_neko as yn
# wipe cache again
from pathlib import Path
for p in [yn._neko_root() / "nat1to1.txt"]:
try:
p.unlink(missing_ok=True)
except Exception:
pass
yn._nat_ip_cache = ""
yn._nat_ip_cached_at = 0.0
ip = yn._detect_public_ip()
print("detected_nat1to1", ip)
desired = max(1, yn._desired_from_db(), 1)
# at least keep currently running count
running = 0
for i in range(1, yn.MAX_INSTANCES + 1):
st = yn._container_state(i)
if st.get("running"):
running = max(running, i)
desired = max(desired, running, 1)
print("desired", desired, "running_upto", running)
text = yn._render_compose(desired)
path = yn._compose_path()
path.write_text(text, encoding="utf-8")
print("compose_nat_line", [ln for ln in text.splitlines() if "NAT1TO1" in ln][:4])
# force recreate all defined services, keep them started if they were up
start = set(range(1, desired + 1)) if running else {{1}}
# Prefer force-recreate so env changes apply
code, out = yn._run(yn._compose_cmd("up", "-d", "--force-recreate", "--no-deps"), timeout=900)
print("compose_up", code, out[-800:])
for i in sorted(start):
st = yn._container_state(i)
print(f"neko{{i}}", st)
print("status", yn.status())
PY
"""
sftp = g.open_sftp()
with sftp.file("/tmp/switch_neko_nat1to1.sh", "w") as f:
f.write(remote)
sftp.close()
print(run(g, f"bash /tmp/switch_neko_nat1to1.sh", 900), flush=True)
# verify container env
print(
run(
g,
"docker inspect douyinweb-neko-1 --format '{{range .Config.Env}}{{println .}}{{end}}' 2>/dev/null | grep -E 'NAT1TO1|UDPMUX|EPR' || true",
30,
),
flush=True,
)
g.close()
print("=== 3) confirm both edges still HTTP-ok + Tencent DNAT ===", flush=True)
print(
run(
v,
"""
curl -sS -m 12 -o /dev/null -w 'com_api=%{http_code}\n' https://dy.nomadro.com/api/health
curl -sS -m 12 -o /dev/null -w 'com_neko=%{http_code}\n' https://dy.nomadro.com/neko/1/
curl -sS -m 12 -o /dev/null -w 'cn_api=%{http_code}\n' https://dy.nomadro.cn/api/health
curl -sS -m 12 -o /dev/null -w 'cn_neko=%{http_code}\n' https://dy.nomadro.cn/neko/1/
curl -sS -m 12 -o /dev/null -w 'dylive=%{http_code}\n' https://dylive.nomadro.com/api/health
""",
50,
),
flush=True,
)
v.close()
d = ssh("82.157.112.245", 22, "ubuntu", "Xiao4669805")
print(
run(
d,
"sudo iptables -t nat -S PREROUTING | grep '52300' | head -4; "
"timeout 2 bash -c 'echo >/dev/tcp/10.9.0.2/52300' && echo WG_TCP52300_OK || echo WG_TCP52300_FAIL",
20,
),
flush=True,
)
d.close()
print("DONE — Neko NAT1TO1 → Tencent", flush=True)
print(
"NOTE: If TCP_52300=BLOCKED above, open Tencent Security Group inbound "
"TCP/UDP 52300-52303 and UDP 52000-52299 to 0.0.0.0/0 (or your client ranges).",
flush=True,
)
return 0
if __name__ == "__main__":
raise SystemExit(main())