How can you get the SSH return code using Paramiko?

Beyonder picture Beyonder · Aug 25, 2010 · Viewed 70.3k times · Source
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.

Answer

apdastous picture apdastous · Jan 31, 2013

A much easier example that doesn't involve invoking the "lower level" channel class directly (i.e. - NOT using the client.get_transport().open_session() command):

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('blahblah.com')

stdin, stdout, stderr = client.exec_command("uptime")
print stdout.channel.recv_exit_status()    # status is 0

stdin, stdout, stderr = client.exec_command("oauwhduawhd")
print stdout.channel.recv_exit_status()    # status is 127