using subprocess.popen with ssh - python

1.5k Views Asked by At

i'm trying to run a python script from host to some clients via subprocess.popen. The command is sort of fire and forget and the process in the clients should run for an unlimited time untill i kill it. the problem is - when i run this line in python the process run on the clients for an hour and then suddenly stops after 1 hour and 2 minutes :

subprocess.Popen(["rsh {} {} {}".format(ipClient,command,args)], shell=True)

where "command" is the path and the command in the clients. and when i simply run rsh 'ip' 'command' 'args' in the shell it works as expected and does not stop suddenly.

any idea?

1

There are 1 best solutions below

2
On

While subprocess.Popen might work for wrapping ssh access, this is not the preferred way to do so.

I recommend using paramiko.

import paramiko
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(server, username=user,password=password)
...
ssh_client.close()

And If you want to simulate a terminal, as if a user was typing:

chan=self.ssh_client.invoke_shell()

def exec_cmd(cmd):
    """Gets ssh command(s), execute them, and returns the output"""
    prompt='bash $' # the command line prompt in the ssh terminal
    buff=''
    chan.send(str(cmd)+'\n')
    while not chan.recv_ready():
        time.sleep(1)
    while not buff.endswith(prompt):
        buff+=self.chan.recv(1024)
    return buff[:len(prompt)]

Example usage: exec_cmd('pwd')

If you don't know the prompt in advance, you can set it with:

chan.send('PS1="python-ssh:"\n')