# -*- coding: utf-8 -*- """Continue neko-7 recovery probes.""" from __future__ import annotations import sys import paramiko sys.stdout.reconfigure(encoding="utf-8", errors="replace") PASS = "4669805" # Keep remote script free of Python triple-quote nesting issues. REMOTE_SH = r"""#!/bin/bash set -uo pipefail cat >/tmp/_probe_one.py <<'PY' import json, urllib.request, base64, os, socket, struct, time, sys def tabs(): return json.loads(urllib.request.urlopen("http://127.0.0.1:9222/json/list", timeout=5).read().decode()) def ws_connect(url): hostport, path = url[5:].split("/", 1) path = "/" + path host, port_s = hostport.split(":") port = int(port_s) key = base64.b64encode(os.urandom(16)).decode() sock = socket.create_connection((host, port), timeout=6) req = ( "GET %s HTTP/1.1\r\nHost: %s\r\nUpgrade: websocket\r\nConnection: Upgrade\r\n" "Sec-WebSocket-Key: %s\r\nSec-WebSocket-Version: 13\r\n\r\n" % (path, hostport, key) ).encode() sock.sendall(req) buf = b"" while b"\r\n\r\n" not in buf: chunk = sock.recv(4096) if not chunk: raise RuntimeError("ws closed") buf += chunk return sock def ws_send(sock, payload): data = json.dumps(payload).encode() mask = os.urandom(4) if len(data) < 126: header = bytearray([0x81, 0x80 | len(data)]) else: header = bytearray([0x81, 0x80 | 126]) + struct.pack("!H", len(data)) header.extend(mask) masked = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) sock.sendall(bytes(header) + masked) def ws_recv(sock): def readexact(n): out = b"" while len(out) < n: chunk = sock.recv(n - len(out)) if not chunk: raise RuntimeError("closed") out += chunk return out hdr = readexact(2) b1, b2 = hdr[0], hdr[1] ln = b2 & 0x7F if ln == 126: ln = struct.unpack("!H", readexact(2))[0] elif ln == 127: ln = struct.unpack("!Q", readexact(8))[0] mask = readexact(4) if (b2 & 0x80) else b"" data = readexact(ln) if mask: data = bytes(b ^ mask[i % 4] for i, b in enumerate(data)) if (b1 & 0x0F) != 0x1: return {"id": None} return json.loads(data.decode()) def eval_js(ws_url, expr): sock = ws_connect(ws_url) ws_send(sock, {"id": 1, "method": "Runtime.evaluate", "params": {"expression": expr, "returnByValue": True}}) deadline = time.time() + 6 while time.time() < deadline: msg = ws_recv(sock) if msg.get("id") == 1: sock.close() return ((msg.get("result") or {}).get("result") or {}).get("value") sock.close() return None ts = tabs() print("tab_count", len(ts)) cand = None for t in ts: u = t.get("url") or "" if "studio.youtube.com" in u and "livestreaming" in u: cand = t break if not cand: for t in ts: if t.get("type") == "page" and t.get("webSocketDebuggerUrl"): cand = t break if not cand: print("NO_TAB") raise SystemExit(0) print("focus", (cand.get("title") or "")[:70], "|", (cand.get("url") or "")[:170]) expr = "(function(){var text=(document.body&&document.body.innerText||'').slice(0,3000); var imgs=[].slice.call(document.querySelectorAll('img[alt]')).map(function(i){return i.alt;}).filter(Boolean).slice(0,15); var links=[].slice.call(document.querySelectorAll(\"a[href*='channel/'],a[href*='/@']\")).map(function(a){return (a.href||'')+'|'+(a.innerText||'').trim();}).slice(0,15); return JSON.stringify({title:document.title,href:location.href,text:text,imgs:imgs,links:links});})()" val = eval_js(cand.get("webSocketDebuggerUrl"), expr) print("EVAL", (val or "")[:2800]) PY echo === neko7 === cat /tmp/_probe_one.py | docker exec -i douyinweb-neko-7 python3 - echo === neko3 === cat /tmp/_probe_one.py | docker exec -i douyinweb-neko-3 python3 - echo === proxy neko7 === docker exec douyinweb-neko-7 python3 - <<'PY' import socket, urllib.request try: print("resolve", socket.gethostbyname("host.docker.internal")) except Exception as e: print("resolve_fail", e) s=socket.socket(); s.settimeout(2) print("7890", s.connect_ex(("host.docker.internal",7890))); s.close() proxy=urllib.request.ProxyHandler({"http":"http://host.docker.internal:7890","https":"http://host.docker.internal:7890"}) opener=urllib.request.build_opener(proxy) for url in ["https://www.youtube.com/","https://studio.youtube.com/"]: try: r=opener.open(url, timeout=12) print(url, r.status, (r.geturl() or "")[:120]) except Exception as e: print(url, "ERR", type(e).__name__, str(e)[:160]) PY echo === db === cd /opt/douyinWEB/backend PYTHONPATH=/opt/douyinWEB/backend .venv/bin/python - <<'PY' from app import yt_assign_db, db for g in yt_assign_db.list_groups(include_urls=False): nid=int(g.get("neko_instance_id") or 0) if nid in (3,7): print("assign", nid, g.get("name"), "pk", g.get("channel_pk")) conn=db._connect() try: cols=[r[1] for r in conn.execute("PRAGMA table_info(shorts_channels)").fetchall()] print("shorts_cols", cols) q="SELECT * FROM shorts_channels WHERE youtube_channel_id=? OR lower(name) LIKE ?" rows=conn.execute(q, ("UCjQ8jnBm2N4FGRowNXcXThw","%street%")).fetchall() for row in rows[:5]: d=dict(zip(cols,row)) keep={k:d.get(k) for k in cols if k in ("id","name","youtube_channel_id","email","title","channel_title")} print("shorts", keep) except Exception as e: print("db_err", e) finally: conn.close() PY echo CONT_OK """ def main() -> int: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect( "107.173.30.245", 4014, "eric", PASS, timeout=45, banner_timeout=120, allow_agent=False, look_for_keys=False, ) sftp = c.open_sftp() with sftp.file("/tmp/_neko7_cont.sh", "w") as f: f.write(REMOTE_SH) sftp.close() _, o, e = c.exec_command( f"echo '{PASS}' | sudo -S -p '' bash /tmp/_neko7_cont.sh", timeout=120, ) print((o.read() + e.read()).decode("utf-8", "replace")) c.close() return 0 if __name__ == "__main__": raise SystemExit(main())