aar*_*acy 16 python unix ssh popen
如何向对象中的Ctrl-C
多个ssh -t
进程发送Popen()
?
我有一些Python代码可以启动远程主机上的脚本:
# kickoff.py
# i call 'ssh' w/ the '-t' flag so that when i press 'ctrl-c', it get's
# sent to the script on the remote host. otherwise 'ctrol-c' would just
# kill things on this end, and the script would still be running on the
# remote server
a = subprocess.Popen(['ssh', '-t', 'remote-host', './script.sh', 'a'])
a.communicate()
Run Code Online (Sandbox Code Playgroud)
这很好用,但我需要启动远程主机上的多个脚本:
# kickoff.py
a = subprocess.Popen(['ssh', '-t', 'remote-host', './script.sh', 'a'])
b = subprocess.Popen(['ssh', '-t', 'remote-host', './script.sh', 'b'])
a.communicate()
b.communicate()
Run Code Online (Sandbox Code Playgroud)
结果是Ctrl-C
不能可靠地杀死所有东西,我的终端后来总是乱码(我必须运行'重置').那么当主要文件被杀死时如何杀死两个远程脚本呢?
注意:我正在尝试避免登录到远程主机,在进程列表中搜索"script.sh",并向两个进程发送SIGINT.我只是希望能够按下Ctrl-C
启动脚本,并杀死两个远程进程.一个不太理想的解决方案可能涉及确定性地找到远程脚本的PID,但我不知道如何在我当前的设置中这样做.
更新:在远程服务器上启动的脚本实际上启动了几个子进程,并且杀死它ssh
确实会终止原始远程脚本(可能是SIGHUP的b/c),子任务不会被终止.
我成功杀死所有子进程的唯一方法是使用pexpect:
a = pexpect.spawn(['ssh', 'remote-host', './script.sh', 'a'])
a.expect('something')
b = pexpect.spawn(['ssh', 'remote-host', './script.sh', 'b'])
b.expect('something else')
# ...
# to kill ALL of the children
a.sendcontrol('c')
a.close()
b.sendcontrol('c')
b.close()
Run Code Online (Sandbox Code Playgroud)
这足够可靠.我相信其他人早些时候发布了这个答案,但后来删除了答案,所以我会发布它以防其他人好奇.