douyinWEB/scripts/_fix_dylive_neko_all_404.py
2026-09-13 22:10:49 -05:00

175 lines
6.6 KiB
Python

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Diagnose + fix dylive.nomadro.com /neko/* 404 (all local Nekos)."""
import re
import sys
import time
import httpx
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
VPS = ("107.173.30.245", 22, "root", "Xiao4669805")
def ssh():
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect(*VPS[:2], username=VPS[2], password=VPS[3], timeout=40, allow_agent=False, look_for_keys=False)
return c
def run(c, cmd, timeout=90):
_i, o, e = c.exec_command(cmd, timeout=timeout)
return (o.read() + e.read()).decode("utf-8", "replace")
def main() -> None:
print("=== public ===")
with httpx.Client(timeout=15, follow_redirects=False) as client:
for u in [
"https://dylive.nomadro.com/neko/1",
"https://dylive.nomadro.com/neko/1/",
"https://dylive.nomadro.com/neko/7",
"https://dylive.nomadro.com/neko/7/",
]:
try:
r = client.get(u)
print(u, r.status_code, "loc="+r.headers.get("location", ""), "ct="+r.headers.get("content-type","")[:30])
except Exception as ex:
print(u, ex)
c = ssh()
print(run(c, r"""
echo '=== find dylive caddy ==='
ls -la /etc/caddy/sites/ 2>/dev/null
for f in /etc/caddy/sites/*; do
if grep -q 'dylive.nomadro.com' "$f" 2>/dev/null; then echo FOUND "$f"; fi
done
echo '=== neko handles ==='
grep -nE 'neko|920[0-9]|9199' /etc/caddy/sites/* 2>/dev/null | head -100
echo '=== local neko ports ==='
ss -lntp | grep -E ':920[0-9]|:9199' | head -20
docker ps --format '{{.Names}}' | grep douyinweb-neko | sort
curl -sS -m 3 -o /dev/null -w 'p9200=%{http_code} ' http://127.0.0.1:9200/ || true
curl -sS -m 3 -o /dev/null -w 'p9206=%{http_code}\n' http://127.0.0.1:9206/ || true
"""))
# locate site file
out = run(c, "grep -l 'dylive.nomadro.com' /etc/caddy/sites/* 2>/dev/null | head -1")
site = out.strip().splitlines()[-1].strip() if out.strip() else ""
print("SITE_FILE", site)
if not site:
out2 = run(c, "grep -lR 'dylive.nomadro.com' /etc/caddy /opt/douyinWEB 2>/dev/null | head -10")
print("SEARCH", out2)
c.close()
return
text = run(c, f"cat {site}")
print("=== site head ===")
print("\n".join(text.splitlines()[:40]))
print("=== neko-related lines ===")
for i, line in enumerate(text.splitlines(), 1):
if "neko" in line.lower() or re.search(r"920\d|9199", line):
print(f"{i}:{line}")
# Desired block: redirect bare /neko/N -> /neko/N/ ; proxy all /neko/N/* to 127.0.0.1:9200+(N-1)
# Prefer unlimited pattern like physical gateway if present on :9199, else per-port reverse_proxy for 1..64
has_gw = "9199" in run(c, "ss -lntp | grep 9199 || true")
print("gateway9199", has_gw)
# Build replacement: remove old per-instance neko handles, insert unlimited block
NEKO_BLOCK = r'''
# Neko: bare /neko/N -> /neko/N/ then proxy to localhost 9200+(N-1)
@nekoBare path_regexp nekoBare ^/neko/([0-9]+)$
redir @nekoBare /neko/{re.nekoBare.1}/ 308
@nekoPath path_regexp nekoPath ^/neko/([0-9]+)(/.*)?$
handle @nekoPath {
reverse_proxy {http.request.uri} {
to localhost:9200 localhost:9201 localhost:9202 localhost:9203 localhost:9204 localhost:9205 localhost:9206 localhost:9207 localhost:9208 localhost:9209 localhost:9210 localhost:9211 localhost:9212 localhost:9213 localhost:9214 localhost:9215
lb_policy cookie
}
}
'''
# Caddy can't easily map N->port with lb like that. Use handle_path per instance OR a small gateway.
# Best: use map + rewrite or individual handle_path for 1..32.
lines = []
lines.append("\t# --- neko unlimited (auto) ---")
lines.append("\t@nekoBare path_regexp nekoBare ^/neko/([0-9]+)$")
lines.append("\tredir @nekoBare /neko/{re.nekoBare.1}/ 308")
for i in range(1, 33):
port = 9200 + i - 1
lines.append(f"\thandle_path /neko/{i}/* {{")
lines.append(f"\t\treverse_proxy 127.0.0.1:{port} {{")
lines.append("\t\t\theader_up Host {host}")
lines.append("\t\t\theader_up X-Forwarded-Proto {scheme}")
lines.append("\t\t\theader_up X-Forwarded-Host {host}")
lines.append("\t\t}")
lines.append("\t}")
neko_block = "\n".join(lines) + "\n"
# Strip existing neko handle blocks
cleaned = text
# remove @neko / redir neko / handle_path /neko/N / handle /neko/N
cleaned = re.sub(r"\n\t@nekoBare[\s\S]*?\n\tredir @nekoBare[^\n]*\n", "\n", cleaned)
cleaned = re.sub(r"\n\thandle_path /neko/\d+/\* \{[\s\S]*?\n\t\}\n", "\n", cleaned)
cleaned = re.sub(r"\n\thandle /neko/\d+ \{[\s\S]*?\n\t\}\n", "\n", cleaned)
cleaned = re.sub(r"\n\t# --- neko unlimited \(auto\) ---[\s\S]*?(?=\n\t(?:handle|@|#)|$)", "\n", cleaned)
# also remove older # Neko comments blocks carefully - if gateway style
cleaned = re.sub(
r"\n\t@neko path /neko /neko/\*[\s\S]*?\n\thandle @neko \{[\s\S]*?\n\t\}\n",
"\n",
cleaned,
)
# Insert neko block after opening brace of site
m = re.search(r"(dylive\.nomadro\.com\s*\{)", cleaned)
if not m:
print("NO_SITE_BRACE")
c.close()
return
insert_at = m.end()
new_text = cleaned[:insert_at] + "\n" + neko_block + cleaned[insert_at:]
# backup + write via sftp then install
bak = f"{site}.bak_neko_{int(time.time())}"
sftp = c.open_sftp()
with sftp.file("/tmp/dylive_neko_fix.caddy", "w") as f:
f.write(new_text)
sftp.close()
print(run(c, f"""
set -e
cp -a {site} {bak}
cat /tmp/dylive_neko_fix.caddy > {site}
# validate
caddy validate --config /etc/caddy/Caddyfile 2>&1 | tail -20
caddy reload --config /etc/caddy/Caddyfile 2>&1 | tail -10
echo RELOADED
"""))
time.sleep(1)
print("=== verify ===")
with httpx.Client(timeout=15, follow_redirects=False) as client:
for u in [
"https://dylive.nomadro.com/neko/1",
"https://dylive.nomadro.com/neko/1/",
"https://dylive.nomadro.com/neko/7",
"https://dylive.nomadro.com/neko/7/",
"https://dylive.nomadro.com/neko/8/",
]:
r = client.get(u)
print(u, r.status_code, "loc="+r.headers.get("location",""), "snip="+r.text[:60].replace("\n"," "))
# follow
with httpx.Client(timeout=15, follow_redirects=True) as client:
for u in ["https://dylive.nomadro.com/neko/7", "https://dylive.nomadro.com/neko/1/"]:
r = client.get(u)
print("FOLLOW", u, r.status_code, r.url, r.text[:50].replace("\n"," "))
c.close()
if __name__ == "__main__":
main()