views:

73

answers:

2
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.

+1  A: 

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 $?')
leoluk
Thanks, but I think command + '; echo $?' may be better :)but I wonder how perl ssh library does it?use Net::SSH::Perl;( $cmdout, $cmderr, $cmdexit ) = $ssh->cmd($command)
Beyonder
It seems that I was wrong. Sorry.
leoluk
+1  A: 

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: 
$
JanC
Really appreciate for your answer!! I've use it in my project.Thank you very much. So far I can use paramiko instead of wrapping system command ssh in programming with python.
Beyonder
It's only something I put together by looking at the source of SSHClient, so it might not be *optimal*. BTW: if this does what you want, you might want to "accept" my answer.
JanC