如何使用Paramiko获取SSH返回码?
发布于 2021-01-29 17:07:27
client = paramiko.SSHClient()
stdin, stdout, stderr = client.exec_command(command)
有什么方法可以获取命令返回码?
很难解析所有stdout / stderr并知道命令是否成功完成。
关注者
0
被浏览
143
1 个回答
-
SSHClient是一个简单的包装类,围绕着Paramiko中的更底层功能。该API文档列出
recv_exit_status()
的方法Channel
类。一个非常简单的演示脚本:
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: $