如何使用Paramiko获取SSH返回码?

Bey*_*der 87 python ssh paramiko

client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)
Run Code Online (Sandbox Code Playgroud)

有没有办法获得命令返回码?

很难解析所有stdout/stderr并知道命令是否成功完成.

小智 255

更简单的示例不涉及直接调用通道类:

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
Run Code Online (Sandbox Code Playgroud)

  • 这是问题的正确解决方案. (42认同)
  • 关于这个例子有什么*不错*不只是捕获E​​XIT(就像问题一样),但是证明你仍然可以获得STDOUT和STDERR.多年前,我被Paramiko的贫穷示例代码库误导(没有不尊重),并且让EXIT我使用低级别的transport()调用.transport()似乎迫使你"选择一个"(这可能不是真的,但缺乏示例和教程文档让我相信)... (3认同)

小智 48

SSHClient是一个简单的包装类,围绕Paramiko中更低级的功能.的API文档列出了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: 
$
Run Code Online (Sandbox Code Playgroud)

  • 这是一个糟糕的解决方案.请参阅下面的@apdastous'答案,它会好得多. (9认同)
  • chan.recv_exit_status() - 当它刚刚挂起并且永不返回时很可爱.很棒的建议. (3认同)

per*_*eed 5

感谢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()
Run Code Online (Sandbox Code Playgroud)