0

I want to run a process on a remote machine and I want it to get terminated when my host program exits.

I have a small test script which looks like this:

import time
while True:
    print('hello')
    time.sleep(1)

and I start this process on a remote machine via a script like this one:

import paramiko

ssh = paramiko.SSHClient()
ssh.load_system_host_keys()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('my_machine', username='root', key_filename='some_key')
_in, _out, _err = ssh.exec_command('python /home/me/loop.py')
time.sleep(5)  # could do something with in/out/err
ssh.close()

But my problem is that the started process keeps running even after I've closed the Python process which started the SSH connection.

Is there a way to force closing the remote session and the remotely started process when the host process gets terminated?

Edit:

This question sounds similar but there is no satisfying answer. I tried to set the keepalive but with no effect:

ssh.get_transport().set_keepalive(1)
Community
  • 1
  • 1
frans
  • 8,868
  • 11
  • 58
  • 132

2 Answers2

2

When the SSH connection is closed it'll not kill the running command on remote host.

The easiest solution is:

ssh.exec_command('python /home/me/loop.py', get_pty=True)
# ... do something ...
ssh.close()

Then when the SSH connection is closed, the pty (on remote host) will also be closed and the kernel (on remote host) will send the SIGHUP signal to the remote command. By default SIGHUP will terminate the process so the remote command will be killed.


According to the APUE book:

SIGHUP is sent to the controlling process (session leader) associated with a controlling terminal if a disconnect is detected by the terminal interface.

pynexj
  • 19,215
  • 5
  • 38
  • 56
  • This works but only for short running processes. After adding get_pty=True, remote process will be terminated after about 10 minutes. I am looking for solution that allows me to kill remotly running processes and allows the processes to run more than 10 minutes. – Łukasz Strugała Jul 18 '23 at 06:53
0

Try closer - a library I've written specifically for this sort of thing. Doesn't use Paramiko, but perhaps it will work for you anyway.