如何使用Paramiko获得SSH返回码?
client = paramiko.SSHClient() stdin, stdout, stderr = client.exec_command(command)
有什么办法可以得到命令的返回码吗?
很难parsing所有的标准输出/标准错误,并知道命令是否成功完成。
SSHClient是Paramiko中较低层function的简单包装类。 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: $
更简单的例子,不涉及直接调用通道类:
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
感谢JanC,我添加了一些修改,并在Python3中进行了testing,对我来说真的很有用。
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()