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

时间:2013-06-16 21:22:37

标签: python 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的操作,文件被复制),但我总是得到“此命令没有输出”。当打印stdout = stdout.readlines()时,[]是输出。另外,如果我在for循环中添加一个print语句,它就永远不会运行。有人可以帮帮我吗?谢谢!

4 个答案:

答案 0 :(得分:12)

您在阅读行之前已关闭连接:

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"

答案 1 :(得分:2)

*互动示例: ====第1部分,这显示了服务器中的sh输出,结束时是">"  需要一些输入才能继续或退出======

selilsosx045:uecontrol-CXC_173_6456-R32A01 lteue $ ./uecontrol.sh -host localhost UE控制:使用以下命令启动UE控制: UE控制:java -Dlogdir = -Duecontrol.configdir =。/ etc -jar ./server/server-R32A01.jar -host localhost 从文件/Users/lteue/Downloads/uecontrol-CXC_173_6456-R32A01/etc/uecontrol.properties加载属性 启动远程CLI到主机localhost 输入命令Q以退出CLI或命令HELP 获取有关可用命令的信息。 CLI已准备好输入。 uec>

=========== pehiko的Pyhton代码============ *

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

答案 2 :(得分:1)

正如@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")

答案 3 :(得分:0)

在不使用stdout的情况下在运行时在控制台/解释器/ shell中打印输出的程序。

导入paramiko

导入xlrd

导入时间

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)

主机= 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详细信息(主机,端口,用户,通过):

   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 Cameras\n")

   time.sleep(5)

   output = remote_conn.recv(10000)

   print(output)

详细信息(主机,端口,用户,通过)