3

So i'm putting together something that uses Paramiko to ssh into remote servers and send commands to the remote connection. Everything is going well so far except for the fact that I cant seem to get Paramiko to return the results of the executed command as a string. Paramiko is returning what looks like an instance of the channel and its status. this is what i'm trying right now:

client = paramiko.SSHClient()
client.load_system_host_keys()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


hostname = 'xxxx'
port = 'xxxxx'
user = 'xxxxx'
password = 'xxxxx'


client.connect(hostname,port,user,password)
do_something(client)






def do_something(client):

    object = client.exec_command('pwd')
    print(object)

the following is what Paramiko is giving me as output when I run the program:

  (<paramiko.ChannelFile from <paramiko.Channel 0 (open) window=2097152 -> 
  <paramiko.Transport at 0x6119f90 (cipher aes128-ctr, 128 bits) (active; 1 
   open chanel(s))>>>,

and the desired output should be something like:

 object = client.exec_command('pwd')
 print(object)

ouput:

  '/var/www/html'

essentially if you enter a command how can I get Paramiko to return the string value instead of the object instance? I have tried a few different methods but I cant seem to get around this! Please Advise! very much appreciated!

jonjonson
  • 31
  • 1
  • 2

1 Answers1

5

From Paramiko's documentation for client.exec_command():

The command’s input and output streams are returned as Python file-like objects representing stdin, stdout, and stderr.

So you would need to grab that stdout stream, and read from it:

stdin, stdout, stderr = client.exec_command('pwd')
string = stdout.read().decode('ascii').strip("\n")
Andrew
  • 73
  • 6
  • Thank you so much, this worked. Do I have to call stdin, stdout, stderr every time I want to read the output? or can i simply set stdout = client.exec_command? – jonjonson Jun 15 '18 at 14:48
  • you wouldn't have any idea why dmidecode isn't working when I pass it as the exec_command argument? it says bash command not found but it works when I do on the machine itself – jonjonson Jun 15 '18 at 15:24
  • You have to read both `stdout` and `stderr` as the same time. As I've commented now in the answer to duplicate question: https://stackoverflow.com/a/8138442/850848 – Martin Prikryl Jun 15 '18 at 19:01
  • Regarding the "command not found", see https://stackoverflow.com/q/31964108/850848 – Martin Prikryl Jun 15 '18 at 19:02
  • Hi Martin, Hope you are still around, I tried looking over some of the fixes you referenced, I tried a few things with not luck getting commands like 'dmidecode, lshw' to run. any additional suggestions? – jonjonson Jun 19 '18 at 14:22