Paramiko 没有 return grep 正确
Paramiko doesn't return grep correctly
我正在为自己构建一个工具,通过 SSH 在我的 VPS 上编写 run/kill 脚本。到目前为止,我能够做到这一点(启动或终止进程),但我无法让 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 脚本杀死哪些 PID(123 和 126)。
奖金问题:我不是很linux有经验,在终端外执行 grep 命令会创建任何我必须手动杀死的 PID 吗?
您可能需要通过将整个语句用单引号传递给另一端的 shell 来转义竖线字符:
ssh_obj.exec_command("sh -c 'ps -fA | grep python'")
或者您可以尝试 运行 pgrep
:
ssh_obj.exec_command('pgrep python')
pgrep
将搜索与搜索字符串 python
匹配的当前 运行 个进程,并将只将进程 ID 发送到标准输出。
我正在为自己构建一个工具,通过 SSH 在我的 VPS 上编写 run/kill 脚本。到目前为止,我能够做到这一点(启动或终止进程),但我无法让 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 脚本杀死哪些 PID(123 和 126)。
奖金问题:我不是很linux有经验,在终端外执行 grep 命令会创建任何我必须手动杀死的 PID 吗?
您可能需要通过将整个语句用单引号传递给另一端的 shell 来转义竖线字符:
ssh_obj.exec_command("sh -c 'ps -fA | grep python'")
或者您可以尝试 运行 pgrep
:
ssh_obj.exec_command('pgrep python')
pgrep
将搜索与搜索字符串 python
匹配的当前 运行 个进程,并将只将进程 ID 发送到标准输出。