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.
Using exec_command() in Paramiko returns a tuple (stdin, stdout, stderr) . Most of the time, you just want to read stdout and ignore stdin and stderr . You can get the output the command by using stdout. read() (returns a string) or stdout.
SSH client & key policies class paramiko.client. SSHClient. A high-level representation of a session with an SSH server. This class wraps Transport , Channel , and SFTPClient to take care of most aspects of authenticating and opening channels.
Paramiko helps you automate repetitive system administration tasks on remote servers. More advanced Paramiko programs send the lines of a script one at a time. It does this rather than transacting all of a command, such as df or last , synchronously to completion.
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
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:
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()
Example of its execution:
$ 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: $
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With