# -*- coding: utf-8 -*- """Patch api.nomadro.cn 443 block for /api/config/ws Upgrade.""" from __future__ import annotations import time from pathlib import Path import paramiko HOST, USER, PASS = "82.157.112.245", "ubuntu", "Xiao4669805" PATCHER = r''' from pathlib import Path import shutil p = Path("/www/server/panel/vhost/nginx/api.nomadro.cn.conf") text = p.read_text(encoding="utf-8") marker = "location /api/config/ws" parts = text.split("listen 443") if len(parts) < 2: raise SystemExit("no 443 block") if marker in parts[1]: print("ssl_ws_already") raise SystemExit(0) lines = [ "", " location /api/config/ws {", " proxy_pass http://127.0.0.1:8010;", " proxy_http_version 1.1;", " proxy_set_header Upgrade $http_upgrade;", ' proxy_set_header Connection "upgrade";', " proxy_set_header Host $host;", " proxy_set_header X-Real-IP $remote_addr;", " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;", " proxy_set_header X-Forwarded-Proto $scheme;", " proxy_read_timeout 3600s;", " proxy_send_timeout 3600s;", " proxy_buffering off;", " }", " location /api/ebook/config/ws {", " proxy_pass http://127.0.0.1:8010;", " proxy_http_version 1.1;", " proxy_set_header Upgrade $http_upgrade;", ' proxy_set_header Connection "upgrade";', " proxy_set_header Host $host;", " proxy_set_header X-Real-IP $remote_addr;", " proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;", " proxy_set_header X-Forwarded-Proto $scheme;", " proxy_read_timeout 3600s;", " proxy_send_timeout 3600s;", " proxy_buffering off;", " }", "", ] snippet = "\n".join(lines) ssl = parts[1] idx = ssl.find("location / {") if idx < 0: raise SystemExit("no location / in 443") ssl2 = ssl[:idx] + snippet + "\n" + ssl[idx:] out = parts[0] + "listen 443" + ssl2 shutil.copy2(p, str(p) + ".bak-ws-ssl") p.write_text(out, encoding="utf-8") print("ssl_ws_patched") ''' def main() -> int: c = paramiko.SSHClient() c.set_missing_host_key_policy(paramiko.AutoAddPolicy()) c.connect(HOST, username=USER, password=PASS, timeout=30, allow_agent=False, look_for_keys=False) sftp = c.open_sftp() with sftp.file("/tmp/patch_ws_ssl.py", "w") as rf: rf.write(PATCHER) sftp.close() cmd = "sudo python3 /tmp/patch_ws_ssl.py && sudo nginx -t && sudo nginx -s reload && rm -f /tmp/patch_ws_ssl.py && echo DONE" _, stdout, _ = c.exec_command(cmd, timeout=90, get_pty=True) while not stdout.channel.exit_status_ready(): if stdout.channel.recv_ready(): print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True) time.sleep(0.05) while stdout.channel.recv_ready(): print(stdout.channel.recv(65536).decode("utf-8", "replace"), end="", flush=True) code = stdout.channel.recv_exit_status() c.close() return code if __name__ == "__main__": raise SystemExit(main())