簡體   English   中英

如何終止使用 python 子進程啟動的遠程進程?

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

首先僅供參考,這是對“如何終止使用 shell=True 啟動的 python 子進程”問題的回答

在這種情況下,用戶正在啟動一個子進程,他想稍后終止它。 我試過了,效果很好。

現在,我想做類似的事情,但在遠程機器上。 遠程機器可以通過ssh訪問沒有問題。

所以我有

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

如您所見,我啟動了一個在遠程機器上運行sar -u 1 > mylog.log的進程。 此進程將開始運行 10 秒后,我希望遠程進程停止。 我要怎么殺??

我認為簡單地說os.killpg(os.getpgid(pro.pid), signal.SIGTERM)不會殺死它,不是嗎?

您所要做的就是proc.terminate()proc.kill() (首選第一個)

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

您的遠程程序將被終止,因為 SSH 會自動終止不再與 SSH session 關聯的進程(大多數人都很難找到)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM