Execute command and wait for it to finish with Python Paramiko

Use exec_command: http://docs.paramiko.org/en/1.16/api/channel.html

stdin, stdout, stderr = ssh.exec_command("my_long_command --arg 1 --arg 2")

The following code works for me:

from paramiko import SSHClient, AutoAddPolicy
import time
ssh = SSHClient()
ssh.set_missing_host_key_policy(AutoAddPolicy())
ssh.connect('111.111.111.111', username="myname", key_filename="/path/to/my/id_rsa.pub", port=1123)
sleeptime = 0.001
outdata, errdata="", ''
ssh_transp = ssh.get_transport()
chan = ssh_transp.open_session()
# chan.settimeout(3 * 60 * 60)
chan.setblocking(0)
chan.exec_command('ls -la')
while True:  # monitoring process
    # Reading from output streams
    while chan.recv_ready():
        outdata += chan.recv(1000)
    while chan.recv_stderr_ready():
        errdata += chan.recv_stderr(1000)
    if chan.exit_status_ready():  # If completed
        break
    time.sleep(sleeptime)
retcode = chan.recv_exit_status()
ssh_transp.close()

print(outdata)
print(errdata)

Please note that command history cannot be executed with ssh as is.
See example here: https://superuser.com/questions/962001/incorrect-output-of-history-command-of-ssh-how-to-read-the-timestamp-info-corre

Leave a Comment