Paramiko - 在 exec_command 期间处理网络故障
Paramiko - Handle network failure during exec_command
我正在用 Paramiko 编写脚本,如果在 exec_command
期间发生网络错误,我想处理它。
使用下面的示例代码,如果从一开始就出现网络错误,它运行良好。该函数正在尝试自行执行,直到建立连接。
但是如果错误发生在函数中间,它不会引发异常,而是 returns 一个空字符串。
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)
感谢您的帮助!
读完命令输出后测试活动连接:
client.get_transport().is_active()
我正在用 Paramiko 编写脚本,如果在 exec_command
期间发生网络错误,我想处理它。
使用下面的示例代码,如果从一开始就出现网络错误,它运行良好。该函数正在尝试自行执行,直到建立连接。
但是如果错误发生在函数中间,它不会引发异常,而是 returns 一个空字符串。
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)
感谢您的帮助!
读完命令输出后测试活动连接:
client.get_transport().is_active()