如何使用 Paramiko 获取 SSH 返回码? [英] How can you get the SSH return code using Paramiko?

查看:159
本文介绍了如何使用 Paramiko 获取 SSH 返回码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有什么办法可以得到命令返回码吗?

Is there any way to get the command return code?

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

It's hard to parse all stdout/stderr and know whether the command finished successfully or not.

推荐答案

SSHClient 是一个简单的包装类,它围绕着 Paramiko 中更底层的功能.API 文档 列出了一个 recv_exit_status() Channel 上的方法 类.

SSHClient is a simple wrapper class around the more lower-level functionality in Paramiko. The API documentation lists a recv_exit_status() method on the Channel class.

一个非常简单的演示脚本:

A very simple demonstration script:

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: 
$

这篇关于如何使用 Paramiko 获取 SSH 返回码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆