Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paramiko: read from standard output of remotely executed command

so I was working with paramiko for some basic SSH testing and I'm not getting any output into stdout. Heres my code.

import paramiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('MyIPAddress',MyPortNumber, username='username', password='password')
output=""
stdin, stdout, stderr = client.exec_command(com)

print "ssh succuessful. Closing connection"
client.close()
print "Connection closed"
stdout=stdout.readlines()
print stdout
print com
for line in stdout:
    output=output+line
if output!="":
    print output
else:
    print "There was no output for this command"

So whenever I run this, the command is executed (as seen by if I do something like a cp, the file is copied), but I always get "There was no output for this command". When stdout=stdout.readlines() is printed, [] is the output. In addition, if I add a print statement into the for loop, it never gets run. Could someone help me out here? Thanks!

like image 917
ollien Avatar asked Jun 16 '13 21:06

ollien


People also ask

How do I get command output in Paramiko?

You can get the output the command by using stdout. read() (returns a string) or stdout. readlines() (returns a list of lines).

What is Paramiko SSHClient ()?

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. A typical use case is: client = SSHClient() client.

How do I use Paramiko in Python?

So, we have created a client object “ssh” of “SSHClient” with the paramiko package. This object calls the automatic policy function of adding unknown keys to perform SSH to remote host servers via the paramiko package. The same object is used to connect the client machine with the host server via the host credentials.

Is Paramiko safe?

Is paramiko safe to use? The python package paramiko was scanned for known vulnerabilities and missing license, and no issues were found. Thus the package was deemed as safe to use.


4 Answers

You have closed the connection before reading lines:

import paramiko
client=paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
com="ls ~/desktop"
client.connect('MyIPAddress',MyPortNumber, username='username', password='password')
output=""
stdin, stdout, stderr = client.exec_command(com)

print "ssh succuessful. Closing connection"
stdout=stdout.readlines()
client.close()
print "Connection closed"

print stdout
print com
for line in stdout:
    output=output+line
if output!="":
    print output
else:
    print "There was no output for this command"
like image 130
jabaldonedo Avatar answered Oct 19 '22 16:10

jabaldonedo


The code in the accepted answer may hang, if the command produces also an error output. See Paramiko ssh die/hang with big output.

An easy solution, if you do not mind merging stdout and stderr, is to combine them into one stream using Channel.set_combine_stderr:

stdin, stdout, stderr = client.exec_command(command)
stdout.channel.set_combine_stderr(True)
output = stdout.readlines()

If you need to read the outputs separately, see Run multiple commands in different SSH servers in parallel using Python Paramiko.

like image 3
Martin Prikryl Avatar answered Oct 19 '22 16:10

Martin Prikryl


*Interactive example : ====Part 1, this show the sh output in server ,at the end of is ">" need some input to continual or exit ======

selilsosx045:uecontrol-CXC_173_6456-R32A01 lteue$ ./uecontrol.sh -host localhost UE Control:Start UE control using: UE Control:java -Dlogdir= -Duecontrol.configdir=./etc -jar ./server/server-R32A01.jar -host localhost Loading properties from file /Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/etc/uecontrol.properties Starting remote CLI towards host localhost Enter the command Q to exit the CLI, or the command HELP to get information on available commands. The CLI is ready for input. uec>

===========Pyhton code with peramiko ============*

Try below method : while not stdout.channel.exit_status_ready():

def shCommand(server_list):
server_IP = server_list[0]
username  = server_list[1]
password  = server_list[2]

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(server_IP,22,username, password)strong text

commandList = ['list \n']
alldata = getUeInfo(ssh,commandList)
ssh.close()

def getUeInfo(ssh,commandList):
data_buffer = ""
num_of_input = 0
stdin, stdout, stderr = ssh.exec_command('cmd')
while not stdout.channel.exit_status_ready():
   solo_line = ""        

   if stdout.channel.recv_ready():

      solo_line = stdout.channel.recv(1024)  # Retrieve the first 1024 bytes
      data_buffer += solo_line               


   if(cmp(solo_line,'uec> ') ==0 ):    #len of solo should be 5 ,
     if num_of_input == 0 :
      data_buffer = ""    
      for cmd in commandList :
       #print cmd
       stdin.channel.send(cmd)
      num_of_input += 1
     if num_of_input == 1 :
      stdin.channel.send('q \n') 
      num_of_input += 1

return data_buffer 
like image 2
kevin yu Avatar answered Oct 19 '22 15:10

kevin yu


As @jabaldonedo said you closed your SSHClient connection before reading the stdout. SSHClient can be used as a context manager. Using the SSHClient as a context manager helps prevent you from trying to access stdout and stderr after the ssh connection is closed. The resulting code in Python3 syntax looks like:

from paramiko import AutoAddPolicy, SSHClient

with SSHClient() as client:
    client.set_missing_host_key_policy(AutoAddPolicy)
    client.connect(
        'MyIPAddress',
        MyPortNumber, 
        username='username', 
        password='password'
    )

    com = "ls ~/desktop"
    stdin, stdout, stderr = client.exec_command(com)

    output = ''
    for line in stdout.readlines()
        output += line

if output:
    print(output)
else:
    print("There was no output for this command")
like image 1
jocassid Avatar answered Oct 19 '22 16:10

jocassid