To be able to do that, you will have to grab the PID of that process after running it, and if you do not want to use "grep" or other kind of filters like this, the shell provides a curious mechanism which consists in executing that process in a new shell and afterwards, reading the PID of that process which has just been run.
Let's see an example.
import paramiko if __name__ == "__main__": ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect("ubuntu-server.local", username="javi", password="xxxxxx") _, stdout, _ = ssh.exec_command("echo $$ ; exec python test.py") pid = stdout.readline() print "PID of the remote process: " + pid _, stdout, _ = ssh.exec_command("ps -eo pid,command | grep %s" % pid) print "Looking for the process:\n" + stdout.read() ssh.exec_command("kill -s SIGINT %s" % pid) ssh.close()
As you can see above, I am running on a remote server a straightforward script called test.py with the following lines.
while True: pass
Before executing the script through exec (replaces the current process image with a new one), I have put the order "echo $$", and in this way, I will be able to dump the PID of that process. Finally, I am using that PID to search for that process by means of ps and kill it. Let's run the module.
$ python remote_pid.py PID of the remote process: 6020 Looking for the process: 6020 python test.py 6021 bash -c ps -eo pid,command | grep 6020 6023 grep 6020