我可以通过paramiko的exec_command在服务器后台运行命令吗?

时间:2012-03-10 17:28:15

标签: python linux ssh paramiko

我使用exec_command的{​​{1}}如下操作在服务器上运行命令

client.exec_command('test > /dev/null 2 > &1 &')

但我无法通过'ps aux | grep test'看到这个过程。

为什么会这样?

2 个答案:

答案 0 :(得分:1)

因为“test”命令以给定表达式确定的状态退出。

该命令在后台运行,但立即退出。

使用另一个命令,你会看到它在后台运行。

罗布

答案 1 :(得分:1)

paramiko为每个.exec_command()生成一个主题,因此您不必添加通常的shell魔法&,就像您在bash中一样。 .exec_command()将立即返回,您必须小心读取其缓冲区(stdin,stdout,sterr)

client.exec_command('test > /dev/null 2 > &1')
time.sleep(5)
client.exec_command('killall -9 test')
...
# the remot command will be force killed if you close the channel. (may depend on sshd implementation)

这将在一个特殊线程中运行test将stderr重定向到stdout。然后主线程将进入休眠状态5秒钟,并生成另一个杀死测试的线程,或者如果您不杀死它,则只需关闭通道,远程sshd将处理会话期间产生的所有触发器

相关问题