14

所以我正在使用 paramiko 进行一些基本的 SSH 测试,但我没有将任何输出输入到标准输出中。这是我的代码。

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 循环中,它永远不会运行。有人可以帮我吗?谢谢!

4

5 回答 5

27

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

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"
于 2013-06-16T21:37:42.953 回答
2

*交互示例: ====Part 1,这显示了服务器中的sh输出,末尾是“>”需要一些输入才能继续或退出======

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

===========带有 peramiko 的 Pyhton 代码 ============*

试试下面的方法: 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 
于 2016-09-28T07:09:53.510 回答
1

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

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

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

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

于 2022-01-26T13:05:51.370 回答
0

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

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")
于 2021-02-22T18:39:45.983 回答
-1
# 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 Cameras\n")

       time.sleep(5)
       output = remote_conn.recv(10000)
       print(output)

 details(Host, Port, User, Pass)

于 2019-05-14T13:49:27.667 回答