paramiko:自动终止远程启动的进程
paramiko: automatically terminate remotely started processes
我想 运行 远程机器上的一个进程,我希望它在我的主机程序退出时终止。
我有一个小测试脚本,如下所示:
import time
while True:
print('hello')
time.sleep(1)
然后我通过如下脚本在远程计算机上启动此过程:
导入参数
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('my_machine', username='root', key_filename='some_key')
_in, _out, _err = ssh.exec_command('python /home/me/loop.py')
time.sleep(5) # could do something with in/out/err
ssh.close()
但我的问题是,即使在我关闭启动 SSH 连接的 Python 进程后,启动的进程仍保持 运行ning。
有没有办法在主机进程终止时强制关闭远程会话和远程启动的进程?
编辑:
This question 听起来很相似,但没有令人满意的答案。我尝试设置 keepalive
但没有效果:
ssh.get_transport().set_keepalive(1)
当 SSH 连接关闭时,它不会终止远程主机上的 运行 命令。
最简单的解决方案是:
ssh.exec_command('python /home/me/loop.py', get_pty=True)
# ... do something ...
ssh.close()
然后当 SSH 连接关闭时,pty(在远程主机上)也将关闭,内核(在远程主机上)将发送 SIGHUP
信号给远程命令。默认情况下 SIGHUP
将终止进程,因此远程命令将被终止。
根据 APUE 书:
SIGHUP is sent to the controlling process (session leader) associated
with a controlling terminal if a disconnect is detected by the terminal
interface.
试试 closer
- 我专门为这类事情编写的库。不使用 Paramiko,但也许它对你有用。
我想 运行 远程机器上的一个进程,我希望它在我的主机程序退出时终止。
我有一个小测试脚本,如下所示:
import time
while True:
print('hello')
time.sleep(1)
然后我通过如下脚本在远程计算机上启动此过程:
导入参数
ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('my_machine', username='root', key_filename='some_key')
_in, _out, _err = ssh.exec_command('python /home/me/loop.py')
time.sleep(5) # could do something with in/out/err
ssh.close()
但我的问题是,即使在我关闭启动 SSH 连接的 Python 进程后,启动的进程仍保持 运行ning。
有没有办法在主机进程终止时强制关闭远程会话和远程启动的进程?
编辑:
This question 听起来很相似,但没有令人满意的答案。我尝试设置 keepalive
但没有效果:
ssh.get_transport().set_keepalive(1)
当 SSH 连接关闭时,它不会终止远程主机上的 运行 命令。
最简单的解决方案是:
ssh.exec_command('python /home/me/loop.py', get_pty=True)
# ... do something ...
ssh.close()
然后当 SSH 连接关闭时,pty(在远程主机上)也将关闭,内核(在远程主机上)将发送 SIGHUP
信号给远程命令。默认情况下 SIGHUP
将终止进程,因此远程命令将被终止。
根据 APUE 书:
SIGHUP is sent to the controlling process (session leader) associated with a controlling terminal if a disconnect is detected by the terminal interface.
试试 closer
- 我专门为这类事情编写的库。不使用 Paramiko,但也许它对你有用。