簡體   English   中英

如何使用Paramiko獲取SSH返回碼?

[英]How can you get the SSH return code using Paramiko?

client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)

有沒有辦法獲得命令返回碼?

很難解析所有stdout / stderr並知道命令是否成功完成。

一個更簡單的例子,不涉及直接調用“低級”通道類(即 - 使用client.get_transport().open_session()命令):

import paramiko

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect('blahblah.com')

stdin, stdout, stderr = client.exec_command("uptime")
print stdout.channel.recv_exit_status()    # status is 0

stdin, stdout, stderr = client.exec_command("oauwhduawhd")
print stdout.channel.recv_exit_status()    # status is 127

SSHClient是一個簡單的包裝類,圍繞Paramiko中更低級的功能。 API文檔列出了Channel類的recv_exit_status()方法。

一個非常簡單的演示腳本:

$ cat sshtest.py
import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
client.connect('127.0.0.1', password=pw)

while True:
    cmd = raw_input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print "running '%s'" % cmd
    chan.exec_command(cmd)
    print "exit status: %s" % chan.recv_exit_status()

client.close()

$ python sshtest.py
Password: 
Command to run: true
running 'true'
exit status: 0
Command to run: false
running 'false'
exit status: 1
Command to run: 
$

感謝JanC,我在示例中添加了一些修改並在Python3中進行了測試,這對我來說非常有用。

import paramiko
import getpass

pw = getpass.getpass()

client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.WarningPolicy())
#client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

def start():
    try :
        client.connect('127.0.0.1', port=22, username='ubuntu', password=pw)
        return True
    except Exception as e:
        #client.close()
        print(e)
        return False

while start():
    key = True
    cmd = input("Command to run: ")
    if cmd == "":
        break
    chan = client.get_transport().open_session()
    print("running '%s'" % cmd)
    chan.exec_command(cmd)
    while key:
        if chan.recv_ready():
            print("recv:\n%s" % chan.recv(4096).decode('ascii'))
        if chan.recv_stderr_ready():
            print("error:\n%s" % chan.recv_stderr(4096).decode('ascii'))
        if chan.exit_status_ready():
            print("exit status: %s" % chan.recv_exit_status())
            key = False
            client.close()
client.close()

在我的情況下,輸出緩沖是問題。 由於緩沖,應用程序的輸出不會以非阻塞的方式出現。 您可以在此處找到有關如何在不緩沖的情況下打印輸出的答案: 禁用輸出緩沖 簡而言之,只需使用-u選項運行python,如下所示:

> python -u script.py

暫無
暫無

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

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