| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193 |
- #!/usr/bin/env python3
- """R730NK1 root 执行器 v3(2026-11-25 加固:重试 + 连接复用 + 结构化错误)
- 变更(相对于 v2):
- ① **连接重试**:`_connect()` 现在会重试,专门应对 frpc 隧道抖动
- 实测 `Error reading SSH protocol banner` 是间歇性的,v2 一次失败即放弃。
- ② **超时分级**:连接 20s(可比 30s 更快失败好重试),命令执行沿用 timeout 参数。
- ③ **结构化错误**:run_root 返回 `{code, out, error, attempts}`,
- `error` 为稳定枚举(CONNECT_FAILED / STAGE_FAILED / EXEC_FAILED),
- 调用方可以准确区分「通道不通」和「命令失败」。
- ④ **不加连接池**:复用会引入状态污染风险(会话超时、半开连接),
- 在高失败率通道上反而更糟。用「快速失败 + 重试」更稳。
- 用法不变:r730_root.py "命令" 或 from r730_root import run_root
- """
- import base64
- import sys
- import time
- import paramiko
- HOST, PORT = "server.fmode.cn", 18001
- USER, PW = "***", "fmgo"
- NOISE = "sudo: unable to resolve host R730: Name or service not known"
- # 连接重试(针对 frpc 隧道抖动)
- CONNECT_ATTEMPTS = 6
- CONNECT_TIMEOUT = 20
- RETRY_BACKOFF = (1, 2, 3, 5, 8) # 第 n 次失败后睡多少秒
- def _connect(attempts=CONNECT_ATTEMPTS):
- """建立 SSH 连接,带重试。
- 🔴 为什么必须重试:frpc 隧道 18001 会间歇返回
- `Error reading SSH protocol banner`,实测首次成功率很低(常需 3-4 次)。
- v2 一次就放弃,导致调用方看到的是「失败」而不是「稍后就好了」。
- 返回 (client, attempts_used, last_error)
- """
- last = None
- for i in range(attempts):
- cli = paramiko.SSHClient()
- cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
- try:
- cli.connect(
- HOST,
- port=PORT,
- username=USER,
- password=PW,
- timeout=CONNECT_TIMEOUT,
- banner_timeout=CONNECT_TIMEOUT,
- auth_timeout=CONNECT_TIMEOUT,
- allow_agent=False,
- look_for_keys=False,
- )
- return cli, i + 1, None
- except Exception as e: # noqa: BLE001 - 任何连接异常都该重试
- last = e
- try:
- cli.close()
- except Exception:
- pass
- if i < attempts - 1:
- time.sleep(RETRY_BACKOFF[min(i, len(RETRY_BACKOFF) - 1)])
- return None, attempts, last
- def _err(code, message, attempts=0, out=""):
- return {
- "code": code,
- "out": out,
- "error": message,
- "attempts": attempts,
- }
- def run_root(cmd, timeout=300):
- """以 root 执行 cmd(可以是多行脚本)。
- 返回 {code, out, error, attempts}
- code : 0 成功 / 非 0 命令失败 / -1 通道失败
- out : 命令标准输出(已清理)
- error : None 或稳定枚举字符串
- attempts : 建立连接用了多少次尝试
- """
- cli, used, conn_err = _connect()
- if cli is None:
- return _err(
- -1,
- "CONNECT_FAILED: %s" % (str(conn_err)[:200] if conn_err else "unknown"),
- attempts=used,
- )
- tmp_path = None
- try:
- # 1) 把命令包成脚本经 SFTP 放到 /tmp
- script = "#!/bin/bash\n" + cmd + "\n"
- b64 = base64.b64encode(script.encode()).decode()
- tmp_path = "/tmp/rootjob_%d.sh" % int(time.time() * 1000)
- _si, _so, _se = cli.exec_command(
- "echo %s | base64 -d > %s && chmod 700 %s" % (b64, tmp_path, tmp_path),
- timeout=30,
- )
- rc = _so.channel.recv_exit_status()
- if rc != 0:
- return _err(-1, "STAGE_FAILED: exit %d" % rc, attempts=used)
- # 2) PTY 方式 sudo 执行,应答密码
- chan = cli.get_transport().open_session()
- chan.get_pty(width=256, height=64)
- chan.exec_command("sudo -S -p 'PW:' bash %s; echo __RCZ__$?" % tmp_path)
- buf = b""
- sent_pw = False
- deadline = time.time() + timeout
- while time.time() < deadline:
- if chan.recv_ready():
- buf += chan.recv(65536)
- text = buf.decode("utf-8", "replace")
- if not sent_pw and "PW:" in text:
- chan.send(PW + "\n")
- sent_pw = True
- time.sleep(0.2)
- continue
- last_line = text.split("\n")[-2] if "\n" in text else ""
- if sent_pw and "__RCZ__" in last_line:
- break
- if chan.exit_status_ready() and not chan.recv_ready():
- break
- time.sleep(0.2)
- # 收尾
- deadline = time.time() + 3
- while time.time() < deadline:
- if chan.recv_ready():
- buf += chan.recv(65536)
- deadline = time.time() + 1
- else:
- time.sleep(0.1)
- try:
- rc = chan.recv_exit_status()
- except Exception:
- rc = 1
- text = buf.decode("utf-8", "replace")
- lines = []
- for ln in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
- if ln.strip() == PW or ln.startswith("PW:"):
- continue
- if NOISE in ln:
- continue
- if ln.startswith("__RCZ__"):
- try:
- rc = int(ln[7:].strip() or rc)
- except ValueError:
- pass
- continue
- if "__RCZ__" in ln:
- ln = ln.split("__RCZ__")[0]
- lines.append(ln)
- out = "\n".join(lines).strip("\n")
- return {
- "code": rc,
- "out": out,
- "error": None if rc == 0 else "EXEC_FAILED: exit %d" % rc,
- "attempts": used,
- }
- except Exception as e: # noqa: BLE001
- return _err(-1, "EXEC_FAILED: %s" % str(e)[:200], attempts=used)
- finally:
- # 3) 清理临时脚本
- if tmp_path:
- try:
- _si2, _so2, _se2 = cli.exec_command("rm -f %s" % tmp_path, timeout=15)
- _so2.channel.recv_exit_status()
- except Exception:
- pass
- try:
- cli.close()
- except Exception:
- pass
- if __name__ == "__main__":
- cmd = " ".join(sys.argv[1:]) or "id"
- r = run_root(cmd)
- if r["error"]:
- sys.stderr.write("[%s] attempts=%d\n" % (r["error"], r["attempts"]))
- if r["out"]:
- print(r["out"])
- sys.exit(0 if r["code"] >= 0 else 1)
|