简体   繁体   English

如何终止使用 python 子进程启动的远程进程?

[英]How can I terminate a remote process that I launched with a python subprocess?

First just for reference here is an answer to the question "How to terminate a python subprocess launched with shell=True"首先仅供参考,这是对“如何终止使用 shell=True 启动的 python 子进程”问题的回答

In this the user is launching a subprocess and he wants to terminate it later.在这种情况下,用户正在启动一个子进程,他想稍后终止它。 I have tried it, it works fine.我试过了,效果很好。

Now, I want to do something similar but in a remote machine.现在,我想做类似的事情,但在远程机器上。 The remote machine can be accessed through ssh with no problem.远程机器可以通过ssh访问没有问题。

so I have所以我有

import os
import signal
import subprocess
import time


SERVER = "remote_server"

#Here initiate a subprocess that measures the cpu but this time remotely
pro= subprocess.Popen("ssh "+SERVER+ " sar -u 1 > mylog.log")

time.sleep(10)

#here kill the process (what should I put HERE??
#Kill the remote process

As you can see I initiate a process that runs sar -u 1 > mylog.log in a remote machine.如您所见,我启动了一个在远程机器上运行sar -u 1 > mylog.log的进程。 This process will start running After 10 secs, I want the remote process to stop.此进程将开始运行 10 秒后,我希望远程进程停止。 How do I kill it??我要怎么杀??

I think putting simply os.killpg(os.getpgid(pro.pid), signal.SIGTERM) would not kill it, would it?我认为简单地说os.killpg(os.getpgid(pro.pid), signal.SIGTERM)不会杀死它,不是吗?

All you have to do is proc.terminate() or proc.kill() (prefer the first one)您所要做的就是proc.terminate()proc.kill() (首选第一个)

See https://docs.python.org/3/library/subprocess.html#subprocess.Popen.killhttps://docs.python.org/3/library/subprocess.html#subprocess.Popen.kill

Your remote program will be killed, because SSH automatically kills off processes that are no longer associated with an SSH session (which most people find out the hard way)您的远程程序将被终止,因为 SSH 会自动终止不再与 SSH session 关联的进程(大多数人都很难找到)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM