diff --git a/datasource/ssh_tunnel.py b/datasource/ssh_tunnel.py index fb54a61..6ec1e28 100644 --- a/datasource/ssh_tunnel.py +++ b/datasource/ssh_tunnel.py @@ -42,6 +42,25 @@ class SSHTunnelManager: key_path = str(project_root / key_path) self.key_path = key_path + def _cleanup_old_processes(self): + """清理残留的同端口SSH进程""" + try: + # 查找监听同一端口的SSH进程 + result = subprocess.run( + ['pgrep', '-f', f'ssh.*-D.*{self.local_port}'], + capture_output=True, text=True + ) + if result.returncode == 0 and result.stdout.strip(): + pids = result.stdout.strip().split('\n') + for pid in pids: + try: + subprocess.run(['kill', '-9', pid], check=True) + print(f" 清理残留SSH进程: PID {pid}") + except subprocess.CalledProcessError: + pass + except Exception: + pass # pgrep不可用或其他问题,忽略 + def start(self) -> bool: """启动SSH隧道""" if not self.enabled: @@ -51,6 +70,9 @@ class SSHTunnelManager: print("SSH配置不完整,跳过隧道建立") return False + # 先清理残留的同端口SSH进程 + self._cleanup_old_processes() + print(f"建立SSH隧道: {self.host}:{self.port} -> 本地SOCKS5端口 {self.local_port}") cmd = [