从paramiko获得PID

时间:2012-03-26 13:18:49

标签: python paramiko

我找不到一个简单的答案:我正在使用paramiko登录并远程执行多个进程,我需要每个进程的PID,以便以后检查它们。在paramiko中似乎没有函数来获取已执行命令的PID,所以我尝试使用以下内容:

stdin,stdout,stderr = ssh.exec_command('./someScript.sh &;echo $!;)

我认为然后通过stdout解析将返回PID,但事实并非如此。我假设我应该在后台运行脚本以获得PID(当它运行时)。有没有更简单明了的获取PID的方法?

2 个答案:

答案 0 :(得分:10)

以下是获取远程进程ID的方法:

def execute(channel, command):
    command = 'echo $$; exec ' + command
    stdin, stdout, stderr = channel.exec_command(command)
    pid = int(stdout.readline())
    return pid, stdin, stdout, stderr

答案 1 :(得分:0)

我通常使用标准UNIX命令pidof <command name>,稍后我会检查该过程。 AFAIK没有简单的方法。

好的,鉴于您的评论,您可以通过将./someScript.sh包装在使用子进程模块的Python进程中来解决它。

wrapper.py:

import subprocess
import sys
proc = subprocess.Popen(sys.argv[1])
print proc.pid
proc.wait() #probably

然后运行

stdin,stdout,stderr = ssh.exec_command('./wrapper.py ./someScript.sh')

并阅读输出

相关问题