python - 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)
谢谢你的帮助!
解决方案
完成读取命令输出后测试活动连接:
client.get_transport().is_active()
推荐阅读
- javascript - Mongodb 查询 vs JavaScript 数组方法性能
- php - 如何在 $pdf->cell() 中回显 cod39 值或将其存储在变量中并在表格中打印结果?
- python - 如何从 x 轴上显示的 sns.distplot 中的 pandas df 获取实际值
- arrays - 如何用golang中的另一个初始化别名数组?
- mips - 如何将 MIPS I 格式转换为二进制?
- json - 如何将多个对象类型的数组转换为 JSON 而不会丢失 Swift 中的任何对象属性?
- database - GridDB server 4.6.0-1 for Ubuntu 20.04
- r - 如何使用 Tidyverse 在 R 中聚合混乱的季度数据,搜索第一组连续的四个季度
- spring - Spring在另一个端口上使用正文(json)重定向简单的rest POST
- python - 我有一个 rgba 图像,我想改变整体颜色