1

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?

KansaiRobot
  • 7,564
  • 11
  • 71
  • 150
  • Did Hack5's solution below work for this use case? I'm looking for a solution for the same problem. – Vijay Jan 18 '22 at 06:31

1 Answers1

0

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)

Hack5
  • 3,244
  • 17
  • 37
  • you mean remotely? (through another Popen)? – KansaiRobot Jun 10 '20 at 08:57
  • so if I kill the SSH process , I will be killing also the process in the remote? – KansaiRobot Jun 10 '20 at 08:58
  • Yes, because the other end of the ssh connection (the daemon) will terminate unused stuff. That's an implementation detail though, you should avoid using it – Hack5 Jun 10 '20 at 08:59
  • if I should avoid it, is there an alternative? – KansaiRobot Jun 10 '20 at 09:02
  • 1
    If you control the remote program, you could program it to read from stdin and exit if it receives any newline character - then you can use `proc.stdin.write("\n")` and it will terminate - but of course that won't work if it crashes. Alternatively, it could write its own PID to stdout, and you can read it, and use a remote `kill` command over ssh, but it's also fallible. – Hack5 Jun 10 '20 at 09:05