client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)
Is there any way to get the command return code?
It's hard to parse all stdout/stderr and know whether the command finished successfully or not.
client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)
Is there any way to get the command return code?
It's hard to parse all stdout/stderr and know whether the command finished successfully or not.
Paramiko can't see more than you would see in a normal SSH session, so you see no exit codes by default.
Solution: you have to change your command to make it return the exit code.
command | echo $?
should work fine on Bash.
client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command + '| echo $?')
SSHClient is a simple wrapper class around the more lower-level functionality in Paramiko. The API documentation lists a recv_exit_status() method on the Channel class.
A very simple demonstration script:
$ cat sshtest.py
import paramiko
import getpass
pw = getpass.getpass()
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', password=pw)
while True:
cmd = raw_input("Command to run: ")
if cmd == "":
break
chan = client.get_transport().open_session()
print "running '%s'" % cmd
chan.exec_command(cmd)
print "exit status: %s" % chan.recv_exit_status()
client.close()
$ python sshtest.py
Password:
Command to run: true
running 'true'
exit status: 0
Command to run: false
running 'false'
exit status: 1
Command to run:
$