簡體   English   中英

Python SSH沒有給出完整的輸出

[英]Python SSH not giving full output

我正在嘗試編寫一個腳本,該腳本登錄到遠程計算機上,運行命令並返回輸出。 我正在使用paramiko庫在python中進行此操作。 但是,由於某種原因,並未產生完整的輸出,僅產生了一行。

為了解決此問題,我創建了一個名為simple的本地腳本,該腳本運行命令並將輸出發送到文件remote_test_output.txt。 然后,我只需將文件sftp過去。 該文件僅包含同一行。 每次輸出的唯一行都是相同的:命令的響應代碼。

當我手動完成所有操作(ssh over,登錄並運行./simple)時,它們都按預期工作,並且輸出文件正確。 但是,通過我的計算機上的腳本進行操作時,它僅返回單行。

我的代碼:

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.load_host_keys(os.path.expanduser(os.path.join("~", ".ssh", "known_hosts")))
ssh.connect(host, username, password)

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command('LD_LIBRARY_PATH=/opt/bin ./simple\n')

print "output:", ssh_stdout.read()+"end" #Reading output of the executed command
print "err:", ssh_stderr.read()#Reading the error stream of the executed command


sftp = ssh.open_sftp()
sftp.get('remote_test_output.txt', 'local_test_output.txt')
sftp.close()

返回什么:

response code: 128

應該返回什么:

field1:value1
field2:value2
response code: 128
field3:value3
field4:value4
etc

有誰知道為什么我要調用的命令無法正常輸出?

我必須包括LD_LIBRARY_PATH變量賦值,否則會得到一個不存在的庫錯誤。

根據paramiko的文檔,“ exec_command”方法返回Channel對象。 第一個問題:您是否嘗試將bufsize參數設置為一個? Channel對象“表現得像套接字”。 因此在文檔中說:

http://www.facebook.com/photo.php?fbid=149324975212197&set=a.128010850676943.34896.126277080850320&type=1&ref=nf

這意味着recv()(可能還有read())將僅讀取讀取緩沖區中的數據。 因此,只要您的read()調用返回,並不意味着該過程已經在遠程端執行。 您應該使用exit_status_ready()方法檢查命令是否已執行:

http://www.lag.net/paramiko/docs/paramiko.Channel-class.html#exit_status_ready

之后,您才能讀取所有數據。 好吧,這就是我的猜測。 我可能是錯的,但是現在我無法檢驗我的理論。

暫無
暫無

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

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