r730_root_v3.py 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. #!/usr/bin/env python3
  2. """R730NK1 root 执行器 v3(2026-11-25 加固:重试 + 连接复用 + 结构化错误)
  3. 变更(相对于 v2):
  4. ① **连接重试**:`_connect()` 现在会重试,专门应对 frpc 隧道抖动
  5. 实测 `Error reading SSH protocol banner` 是间歇性的,v2 一次失败即放弃。
  6. ② **超时分级**:连接 20s(可比 30s 更快失败好重试),命令执行沿用 timeout 参数。
  7. ③ **结构化错误**:run_root 返回 `{code, out, error, attempts}`,
  8. `error` 为稳定枚举(CONNECT_FAILED / STAGE_FAILED / EXEC_FAILED),
  9. 调用方可以准确区分「通道不通」和「命令失败」。
  10. ④ **不加连接池**:复用会引入状态污染风险(会话超时、半开连接),
  11. 在高失败率通道上反而更糟。用「快速失败 + 重试」更稳。
  12. 用法不变:r730_root.py "命令" 或 from r730_root import run_root
  13. """
  14. import base64
  15. import sys
  16. import time
  17. import paramiko
  18. HOST, PORT = "server.fmode.cn", 18001
  19. USER, PW = "***", "fmgo"
  20. NOISE = "sudo: unable to resolve host R730: Name or service not known"
  21. # 连接重试(针对 frpc 隧道抖动)
  22. CONNECT_ATTEMPTS = 6
  23. CONNECT_TIMEOUT = 20
  24. RETRY_BACKOFF = (1, 2, 3, 5, 8) # 第 n 次失败后睡多少秒
  25. def _connect(attempts=CONNECT_ATTEMPTS):
  26. """建立 SSH 连接,带重试。
  27. 🔴 为什么必须重试:frpc 隧道 18001 会间歇返回
  28. `Error reading SSH protocol banner`,实测首次成功率很低(常需 3-4 次)。
  29. v2 一次就放弃,导致调用方看到的是「失败」而不是「稍后就好了」。
  30. 返回 (client, attempts_used, last_error)
  31. """
  32. last = None
  33. for i in range(attempts):
  34. cli = paramiko.SSHClient()
  35. cli.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  36. try:
  37. cli.connect(
  38. HOST,
  39. port=PORT,
  40. username=USER,
  41. password=PW,
  42. timeout=CONNECT_TIMEOUT,
  43. banner_timeout=CONNECT_TIMEOUT,
  44. auth_timeout=CONNECT_TIMEOUT,
  45. allow_agent=False,
  46. look_for_keys=False,
  47. )
  48. return cli, i + 1, None
  49. except Exception as e: # noqa: BLE001 - 任何连接异常都该重试
  50. last = e
  51. try:
  52. cli.close()
  53. except Exception:
  54. pass
  55. if i < attempts - 1:
  56. time.sleep(RETRY_BACKOFF[min(i, len(RETRY_BACKOFF) - 1)])
  57. return None, attempts, last
  58. def _err(code, message, attempts=0, out=""):
  59. return {
  60. "code": code,
  61. "out": out,
  62. "error": message,
  63. "attempts": attempts,
  64. }
  65. def run_root(cmd, timeout=300):
  66. """以 root 执行 cmd(可以是多行脚本)。
  67. 返回 {code, out, error, attempts}
  68. code : 0 成功 / 非 0 命令失败 / -1 通道失败
  69. out : 命令标准输出(已清理)
  70. error : None 或稳定枚举字符串
  71. attempts : 建立连接用了多少次尝试
  72. """
  73. cli, used, conn_err = _connect()
  74. if cli is None:
  75. return _err(
  76. -1,
  77. "CONNECT_FAILED: %s" % (str(conn_err)[:200] if conn_err else "unknown"),
  78. attempts=used,
  79. )
  80. tmp_path = None
  81. try:
  82. # 1) 把命令包成脚本经 SFTP 放到 /tmp
  83. script = "#!/bin/bash\n" + cmd + "\n"
  84. b64 = base64.b64encode(script.encode()).decode()
  85. tmp_path = "/tmp/rootjob_%d.sh" % int(time.time() * 1000)
  86. _si, _so, _se = cli.exec_command(
  87. "echo %s | base64 -d > %s && chmod 700 %s" % (b64, tmp_path, tmp_path),
  88. timeout=30,
  89. )
  90. rc = _so.channel.recv_exit_status()
  91. if rc != 0:
  92. return _err(-1, "STAGE_FAILED: exit %d" % rc, attempts=used)
  93. # 2) PTY 方式 sudo 执行,应答密码
  94. chan = cli.get_transport().open_session()
  95. chan.get_pty(width=256, height=64)
  96. chan.exec_command("sudo -S -p 'PW:' bash %s; echo __RCZ__$?" % tmp_path)
  97. buf = b""
  98. sent_pw = False
  99. deadline = time.time() + timeout
  100. while time.time() < deadline:
  101. if chan.recv_ready():
  102. buf += chan.recv(65536)
  103. text = buf.decode("utf-8", "replace")
  104. if not sent_pw and "PW:" in text:
  105. chan.send(PW + "\n")
  106. sent_pw = True
  107. time.sleep(0.2)
  108. continue
  109. last_line = text.split("\n")[-2] if "\n" in text else ""
  110. if sent_pw and "__RCZ__" in last_line:
  111. break
  112. if chan.exit_status_ready() and not chan.recv_ready():
  113. break
  114. time.sleep(0.2)
  115. # 收尾
  116. deadline = time.time() + 3
  117. while time.time() < deadline:
  118. if chan.recv_ready():
  119. buf += chan.recv(65536)
  120. deadline = time.time() + 1
  121. else:
  122. time.sleep(0.1)
  123. try:
  124. rc = chan.recv_exit_status()
  125. except Exception:
  126. rc = 1
  127. text = buf.decode("utf-8", "replace")
  128. lines = []
  129. for ln in text.replace("\r\n", "\n").replace("\r", "\n").split("\n"):
  130. if ln.strip() == PW or ln.startswith("PW:"):
  131. continue
  132. if NOISE in ln:
  133. continue
  134. if ln.startswith("__RCZ__"):
  135. try:
  136. rc = int(ln[7:].strip() or rc)
  137. except ValueError:
  138. pass
  139. continue
  140. if "__RCZ__" in ln:
  141. ln = ln.split("__RCZ__")[0]
  142. lines.append(ln)
  143. out = "\n".join(lines).strip("\n")
  144. return {
  145. "code": rc,
  146. "out": out,
  147. "error": None if rc == 0 else "EXEC_FAILED: exit %d" % rc,
  148. "attempts": used,
  149. }
  150. except Exception as e: # noqa: BLE001
  151. return _err(-1, "EXEC_FAILED: %s" % str(e)[:200], attempts=used)
  152. finally:
  153. # 3) 清理临时脚本
  154. if tmp_path:
  155. try:
  156. _si2, _so2, _se2 = cli.exec_command("rm -f %s" % tmp_path, timeout=15)
  157. _so2.channel.recv_exit_status()
  158. except Exception:
  159. pass
  160. try:
  161. cli.close()
  162. except Exception:
  163. pass
  164. if __name__ == "__main__":
  165. cmd = " ".join(sys.argv[1:]) or "id"
  166. r = run_root(cmd)
  167. if r["error"]:
  168. sys.stderr.write("[%s] attempts=%d\n" % (r["error"], r["attempts"]))
  169. if r["out"]:
  170. print(r["out"])
  171. sys.exit(0 if r["code"] >= 0 else 1)