首页 > 解决方案 > Paramiko - 在 exec_command 期间处理网络故障

问题描述

我正在用 Paramiko 编写一个脚本,如果它发生在exec_command.

使用下面的示例代码,如果从一开始就出现网络错误,它就可以正常工作。该函数试图自行执行,直到建立连接。

但是如果错误发生在函数的中间,它不会引发异常,而是返回一个空字符串。

def execute(command, connection):
    try:
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        client.connect(connection.host, username=connection.username, password=connection.password)
        log("Command: "+command, YELLOW)

        dummy_stdin, stdout, stderr = client.exec_command("source ~/.bash_profile > \
                                                          /dev/null; "+command)
        err = stderr.read()
        res = stdout.read()
        client.close()

        if err.strip() == "OK":
            log(err.strip(), BLANK)
            return err.strip()
        elif err != '':
            log(err.strip(), RED)
            sys.exit()
        else:
            log(res.strip(), BLANK)
            return res.strip()

    except:
        log("Network failure. Trying again ...", RED)
        return execute(command, connection)

谢谢你的帮助!

标签: pythonsshparamiko

解决方案


完成读取命令输出后测试活动连接:

client.get_transport().is_active()

推荐阅读