Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return Paramiko exec_commmand as a string to python client [duplicate]

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!

like image 361
jonjonson Avatar asked May 13 '26 04:05

jonjonson


1 Answers

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")
like image 61
Andrew Avatar answered May 14 '26 19:05

Andrew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!