# -*- coding: utf-8 -*- """网络自检:端口被被控端占用时,主动询问是否先关掉它再抓包。 原来的流程走不通: 自检要监听 8765/8766,但被控端正占着 -> 绑不上 -> 抓不到任何包。 用户会以为"自检坏了"。 现在: 检测到占用且确实是被控端时,问一句 「要自动关掉被控端并继续抓包吗?(Y/N)」 Y -> 结束被控端进程,重新绑定,继续抓包 N -> 明确说明"这是正常的,不是故障" """ from __future__ import annotations import sys from pathlib import Path TARGET = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote\tools\网络自检.py") OLD_AGENT = '''def agent_running() -> bool: """被控端是不是正在运行(它会占着 8765/8766)。""" text = run(["tasklist", "/FI", "IMAGENAME eq LanRemote-Agent.exe"]) return "LanRemote-Agent" in text ''' NEW_AGENT = '''def agent_running() -> bool: """被控端是不是正在运行(它会占着 8765/8766)。""" text = run(["tasklist", "/FI", "IMAGENAME eq LanRemote-Agent.exe"]) return "LanRemote-Agent" in text def stop_agent() -> bool: """结束被控端进程,好让自检能绑上端口。""" run(["taskkill", "/IM", "LanRemote-Agent.exe", "/F"]) time.sleep(1.5) return not agent_running() def ask_stop_agent() -> bool: """询问是否关掉被控端。非交互环境直接返回 False。""" if not sys.stdin.isatty(): return False line() line(" 被控端正在运行,占着 8765/8766,本自检绑不上端口。") line(" 要抓包必须先让它让出端口。") line() try: answer = input(" >>> 现在自动关掉被控端并继续抓包吗?(Y/N) ").strip().lower() except Exception: return False if not answer.startswith("y"): line(" 好,那本次不抓包。") line(" (这不是故障 —— 被控端在跑就说明它能收到包;") line(" 想抓包时先在它窗口点「退出」再重跑本脚本。)") return False if stop_agent(): line(" 已关闭被控端,继续抓包。") line(" 抓完记得重新启动它。") return True line(" [警告] 关闭失败,可能是权限不够。请手动在它窗口点「退出」。") return False ''' OLD_MAIN = ''' title(f"4. 开始监听({LISTEN_SECONDS} 秒)") if bind_errors and agent_running(): line(" 注意:被控端占着端口,本次抓不到包(这不是故障)。") line(" 要抓包请先退出被控端。") line() ''' NEW_MAIN = ''' title(f"4. 开始监听({LISTEN_SECONDS} 秒)") if agent_running(): ask_stop_agent() line() ''' def main() -> int: text = TARGET.read_text(encoding="utf-8") ok = True for old, new, tag in ((OLD_AGENT, NEW_AGENT, "关被控端"), (OLD_MAIN, NEW_MAIN, "主流程询问")): if old not in text: print(f" [失败] {tag} 锚点未匹配") ok = False else: text = text.replace(old, new, 1) print(f" {tag}: OK") if ok: TARGET.write_text(text, encoding="utf-8") print("\n语法检查:") import ast try: ast.parse(TARGET.read_text(encoding="utf-8")) print(" 网络自检.py: OK") except SyntaxError as exc: print(f" 语法错误 {exc}") ok = False return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())