Skip to main content
 首页 » 编程设计

python之终止由 Python pexpect spawn 创建的 ssh 连接

2025年02月15日8myhome

我已经使用 python pexpect.spawn() 命令创建了一个 SSH 隧道。我想在处理后关闭或终止此 ssh 连接。我试过给<sshtunnel>.close()/<sshtunnel>.kill()/<sshtunnel>.terminate()命令。即使,给出 <sshtunnel>.isalive()方法我得到一个值 False这意味着子进程已经关闭,我仍然看到 ssh 隧道进程在我的 linux ubuntu 机器上运行。

关于如何终止此 ssh 隧道进程的任何输入? 这是简短的代码片段。

    username="username" 
    passwd="password" 
    try: 
        child=pexpect.spawn("ssh -C2qTnNf -D XXXX xxxx@qualifier1.qualifier2.net") 
        i=child.expect('password:') 
        print(i) 
        if i==0: 
            print(passwd) 
            time.sleep (0.5) 
            child.sendline(passwd) 
            child.expect('$') 
            time.sleep(2)  
            print(child) 
            print(child.isalive()) 
            print('####') 
            child.close(force=True) 
           #child.terminate(force=True) 
            time.sleep(5) 
            print(child.isalive()) 
            print(child) 
    except Exception as e: 
        print(str(e)) 

请您参考如下方法:

ssh -f 会 fork 一个在后台运行的子 ssh 进程(如 daemon ),父进程会立即退出。

对于 pexpect.spawn('ssh -f ...'),pexpect 只能与父 ssh 进程交互,因此它无法停止后台 tunnel ssh 进程.

要终止隧道 ssh 进程,您需要找到它的 PID 并执行类似 os.system('kill ...') 或 os.kill(pid, sig).