Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can you get the SSH return code using Paramiko?

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.

like image 327
Beyonder Avatar asked Aug 25 '10 02:08

Beyonder


People also ask

How do I get stdout from Paramiko?

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.

What is Paramiko SSHClient ()?

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.

What can you do with Paramiko?

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.


2 Answers

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 
like image 92
apdastous Avatar answered Sep 25 '22 22:09

apdastous


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:  $ 
like image 35
JanC Avatar answered Sep 23 '22 22:09

JanC