Paramiko:从远程执行命令的标准输出读取



所以我正在使用paramiko进行一些基本的SSH测试,我没有得到任何输出到stdout。这是我的代码。

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"

因此,每当我运行这个命令时,命令就会被执行(如果我执行cp之类的操作,文件就会被复制),但我总是得到"There was no output for this command"。当输出stdout=stdout.readlines()时,输出为[]。此外,如果我在for循环中添加一个print语句,它永远不会运行。有人能帮我一下吗?谢谢!

您在读取行之前已经关闭了连接:

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"

如果命令也产生错误输出,则接受的答案中的代码可能会挂起。参见Paramiko ssh die/hang with big output。

如果您不介意合并stdoutstderr,一个简单的解决方案是使用Channel.set_combine_stderr将它们合并为一个流:

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

如果您需要单独读取输出,请参见使用Python Paramiko在不同的SSH服务器中并行运行多个命令。

*交互示例:====第1部分,这显示了服务器上的sh输出,末尾是">"需要一些输入来继续或退出======

selilsosx045: ucontrol - cxc_173_6456 - r32a01 lteue$ ./ucontrol .sh -host localhostUE控制:启动UE控制使用:UE控制:java -Dlogdir= - ducontrol .configdir=。/etc -jar ./server/server- r32a01 .jar -host localhost ./从文件/Users/lteue/Downloads/ucontrol - cxc_173_6456 - r32a01/etc/ucontrol .properties加载属性向主机localhost启动远程CLI输入命令Q退出CLI,或者输入命令HELP退出CLI获取有关可用命令的信息。已经准备好输入命令行。 uec>

=========== Pyhton代码与peramiko ============*

尝试下面的方法:而不是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 

正如@jabaldonedo所说,您在读取stdout之前关闭了SSHClient连接。SSHClient可以用作上下文管理器。使用SSHClient作为上下文管理器有助于防止在ssh连接关闭后尝试访问stdoutstderr。Python3语法中的结果代码如下:

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")
# Program to print the output in console/interpreter/shell in runtime without using stdout.
 import paramiko
 import xlrd
 import time
 ssh = paramiko.SSHClient()
 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
 loc = ('/Users/harshgow/Documents/PYTHON_WORK/labcred.xlsx')
 wo = xlrd.open_workbook(loc)
 sheet = wo.sheet_by_index(0)
 Host = sheet.cell_value(0, 1)
 Port = int(sheet.cell_value(3, 1))
 User = sheet.cell_value(1, 1)
 Pass = sheet.cell_value(2, 1)
 def details(Host, Port, User, Pass):
       time.sleep(2)
       ssh.connect(Host, Port, User, Pass)
       print('connected to ip ', Host)
       stdin = ssh.exec_command("")
       remote_conn = ssh.invoke_shell()
       print("Interactive SSH session established")
       output = remote_conn.recv(1000)
       remote_conn.send("n")
       remote_conn.send("xstatus Camerasn")
       time.sleep(5)
       output = remote_conn.recv(10000)
       print(output)
 details(Host, Port, User, Pass)

最新更新