0
votes

First just for reference here is an answer to the question "How to terminate a python subprocess launched with shell=True"

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.

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. This process will start running After 10 secs, I want the remote process to stop. How do I kill it??

I think putting simply os.killpg(os.getpgid(pro.pid), signal.SIGTERM) would not kill it, would it?

1

1 Answers

0
votes

All you have to do is proc.terminate() or proc.kill() (prefer the first one)

See https://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)