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

151 lines
5.9 KiB
Python

# -*- coding: utf-8 -*-
"""Start phys Next; deploy hang/login hardenings to VPS; recheck rooms."""
from __future__ import annotations
import json
import sys
import time
import http.cookiejar
import urllib.request
from pathlib import Path
import paramiko
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
ROOT = Path(r"c:\Users\admin\Desktop\douyinWEB")
FILES = [
"backend/app/main.py",
"backend/app/youtube_neko.py",
"backend/app/network_hub.py",
"backend/app/session_auth.py",
"backend/app/shellcrash_hub.py",
"scripts/linux/api_health_watch.sh",
]
def public_login_rooms(base: str) -> None:
cj = http.cookiejar.CookieJar()
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
req = urllib.request.Request(
f"{base}/api/auth/login",
data=json.dumps({"username": "hackrobot", "password": "Xiao4669805@"}).encode(),
headers={"Content-Type": "application/json"},
method="POST",
)
try:
with op.open(req, timeout=25) as r:
print(base, "login", r.status)
except Exception as ex:
print(base, "login ERR", ex)
return
for path in ["/api/auth/status", "/api/rooms?limit=1", "/api/ping", "/api/health"]:
try:
with op.open(f"{base}{path}", timeout=25) as r:
print(base, path, r.status, r.read()[:100])
except Exception as ex:
print(base, path, "ERR", ex)
# --- physical: start next ---
print("=== phys start next ===", flush=True)
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
c.connect("107.173.30.245", 4014, "eric", "4669805", timeout=40, allow_agent=False, look_for_keys=False)
pw = "4669805"
def sh(cmd, t=90):
_, o, e = c.exec_command(f"echo '{pw}' | sudo -S -p '' bash -lc {repr(cmd)}", timeout=t)
return (o.read() + e.read()).decode("utf-8", "replace")
print(sh("ls /etc/systemd/system/douyinweb*.service 2>/dev/null; systemctl list-unit-files 'douyinweb*' | head -40"))
print(sh(
"systemctl start douyinweb-next 2>/dev/null || systemctl start douyinweb-web 2>/dev/null || true; "
"sleep 2; "
"systemctl is-active douyinweb-api douyinweb-api-watch douyinweb-next douyinweb-web 2>/dev/null; "
"ss -ltn sport = :4015; "
"curl -sS -m 5 -o /dev/null -w 'next:%{http_code}\\n' http://127.0.0.1:4015/ || true"
))
# local rooms timing
print(sh(
"python3 - <<'PY'\n"
"import json,time,urllib.request,http.cookiejar\n"
"cj=http.cookiejar.CookieJar(); op=urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))\n"
"t0=time.time()\n"
"req=urllib.request.Request('http://127.0.0.1:8014/api/auth/login',data=json.dumps({'username':'hackrobot','password':'Xiao4669805@'}).encode(),headers={'Content-Type':'application/json'},method='POST')\n"
"print('login',op.open(req,timeout=15).status, round(time.time()-t0,2))\n"
"t0=time.time()\n"
"r=op.open('http://127.0.0.1:8014/api/rooms?limit=1',timeout=30)\n"
"print('rooms',r.status, round(time.time()-t0,2), r.read()[:80])\n"
"PY"
))
c.close()
# --- VPS deploy ---
print("=== vps deploy hardenings ===", flush=True)
v = paramiko.SSHClient()
v.set_missing_host_key_policy(paramiko.AutoAddPolicy())
v.connect("107.173.30.245", 22, "root", "Xiao4669805", timeout=40, allow_agent=False, look_for_keys=False)
sftp = v.open_sftp()
for rel in FILES:
local = ROOT / rel
if not local.is_file():
print("skip missing", rel)
continue
data = local.read_bytes().replace(b"\r\n", b"\n")
tmp = f"/tmp/_dep_{local.name}"
with sftp.file(tmp, "wb") as f:
f.write(data)
dest = f"/opt/douyinWEB/{rel.replace(chr(92), '/')}"
_, o, e = v.exec_command(f"install -D -m 644 {tmp} {dest}; wc -c {dest}", timeout=30)
print(rel, (o.read() + e.read()).decode().strip())
sftp.close()
_, o, e = v.exec_command(
"chmod 755 /opt/douyinWEB/scripts/linux/api_health_watch.sh; "
"bash -n /opt/douyinWEB/scripts/linux/api_health_watch.sh && echo watch_ok; "
"grep -n 'pure in-process\\|_cn_edge_cache\\|/api/ping\\|Let uvicorn bind' "
"/opt/douyinWEB/backend/app/main.py /opt/douyinWEB/backend/app/youtube_neko.py "
"/opt/douyinWEB/backend/app/session_auth.py | head -20; "
"systemctl stop douyinweb-api-watch 2>/dev/null || true; "
"systemctl restart douyinweb-api; "
"sleep 3; systemctl is-active douyinweb-api",
timeout=60,
)
print((o.read() + e.read()).decode())
# wait health
for i in range(36):
time.sleep(5)
_, o, e = v.exec_command(
"curl -sS -m 3 -o /dev/null -w '%{http_code}' http://127.0.0.1:8014/api/health; echo; "
"ss -ltn sport = :8014 | awk 'NR==2{print $2}'",
timeout=20,
)
out = (o.read() + e.read()).decode().strip()
print(f"vps[{i}] {out}", flush=True)
if out.startswith("200"):
break
_, o, e = v.exec_command(
"systemctl reset-failed douyinweb-api-watch 2>/dev/null || true; "
"systemctl start douyinweb-api-watch 2>/dev/null || ("
" # create unit if missing"
" test -f /etc/systemd/system/douyinweb-api-watch.service || cat >/etc/systemd/system/douyinweb-api-watch.service <<'EOF'\n"
"[Unit]\nDescription=douyinWEB API health watchdog\nAfter=douyinweb-api.service\n\n"
"[Service]\nType=simple\nExecStart=/bin/bash /opt/douyinWEB/scripts/linux/api_health_watch.sh\n"
"Restart=always\nRestartSec=5\nEnvironment=DY_API_WATCH_START_GRACE=180\nEnvironment=DY_API_WATCH_FAILS=4\n"
"Environment=DY_API_WATCH_COOLDOWN=180\n\n[Install]\nWantedBy=multi-user.target\nEOF\n"
" systemctl daemon-reload; systemctl enable --now douyinweb-api-watch"
"); "
"sleep 2; systemctl is-active douyinweb-api douyinweb-api-watch; "
"curl -sS -m 3 http://127.0.0.1:8014/api/ping; echo",
timeout=40,
)
print((o.read() + e.read()).decode())
v.close()
print("=== public recheck ===", flush=True)
public_login_rooms("https://dy.nomadro.com")
public_login_rooms("https://dylive.nomadro.com")