簡體   English   中英

Paramiko:從遠程執行命令的標准輸出中讀取

[英]Paramiko: read from standard output of remotely executed command

所以我正在使用 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"

您在閱讀行之前關閉了連接:

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部分,這顯示了服務器中的sh輸出,最后是“>”需要一些輸入才能繼續或退出======

selilsosx045:uecontrol-CXC_173_6456-R32A01 lteue$ ./uecontrol.sh -host localhost UE Con​​trol:Start UE control using: UE Con​​trol: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>

============帶有peramiko的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 

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

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

 details(Host, Port, User, Pass)

如果命令也產生錯誤輸出,則接受的答案中的代碼可能會掛起。 請參閱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 服務器中並行運行多個命令

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM