Paramiko无法正确返回grep

时间:2018-11-20 16:13:30

标签: python python-3.x unix paramiko

我正在为自己构建一个通过SSH在VPS上运行/杀死脚本的工具。到目前为止,我完全能够做到这一点(启动或终止进程),但是我无法设法使ps -fA | grep python命令正常工作。

我的某些脚本实际上是使用Popen生成新脚本的,因此,我确实需要一种通过SSH检查python脚本的PID的方法(以及该PID所属的文件的名称)。

    ssh_obj = self.get_ssh_connection()
    stdin, stdout, stderr = ssh_obj.exec_command('ps -fA | grep python')
    try:
        stdin_read = "stdin: {0}".format(stdin.readline())
    except Exception as e:
        stdin_read = "stdin: ERROR " + str(e)
    try:
        stdout_read = "stdout: {0}".format(stdout.readline())
    except Exception as e:
        stdout_read = "stdout: ERROR " + str(e)
    try:
        stderr_read = "stderr: {0}".format(stderr.readline())
    except Exception as e:
        stderr_read = "stderr: ERROR " + str(e)
    print("\n".join([stdin_read, stdout_read, stderr_read]))

但是它不起作用,显示给我的结果是:

stdin: ERROR File not open for reading
stdout: root       739   738  0 17:12 ?        00:00:00 bash -c ps -fA | grep python
stderr: 

所需的输出如下:

PID: 123 - home/whatever/myfile.py
PID: 125 - home/whatever/myfile2.py
PID: 126 - home/whatever/myfile.py

这样,我将知道要为myfile脚本(123和126)杀死哪些PID。

奖励问题:我不是Linux经验丰富的人,在终端之外执行grep命令会创建我必须手动杀死的PID吗?

1 个答案:

答案 0 :(得分:1)

您可能需要通过将单引号中的整个语句传递到另一端的shell来转义管道字符:

ssh_obj.exec_command("sh -c 'ps -fA | grep python'")

或者,您可以尝试运行pgrep

ssh_obj.exec_command('pgrep python')

pgrep将搜索与搜索字符串python匹配的当前正在运行的进程,并将仅进程ID发送到标准输出。