python - Python:使用parallel-ssh将ssh命令发送到多个服务器,如果其中一个不可用,则会完全失败
问题描述
我用这种方式:
servers = ["192.168.100.161", "192.168.100.162", "192.168.100.163"]
top_command = "top -b -n 1"
host_config = make_host_config(servers)
client = ParallelSSHClient(servers, timeout=2, num_retries=1, retry_delay=1, host_config=host_config)
try:
output = client.run_command(top_command, sudo=True)
print([(k, [x for x in v.stdout], [x for x in v.stderr]) for (k, v) in output.items()])
for host, host_response in output:
print(host, host_response)
except Exception as e:
print("failed to connect some host: ", e)
我现在得到了什么:一个例外。
无法连接某些主机: (“连接到主机 '%s:%s' 时出错 - %s - 重试 %s/%s”, '192.168.100.161', 22, 'timed out', 1, 1)
我希望得到: 来自可用服务器的响应来自不可用服务器的错误
怎么实现啊各位?
解决方案
在针对主机(ip、端口)执行代码之前,我导入套接字模块以测试我连接的端口。在下面的示例中,它是一个 TCP 测试,用于测试 MySQL 的 3306 端口是否已启动。我在函数 connection_test_result 之外实例化了一个空变量,它由 test_connection 函数填充(见下文)。代码执行函数读取 connection_test_result 并在结果为 == 0 时执行。也许这会有所帮助:
def test_connection(ip, port):
global connection_test_result
socket.setdefaulttimeout(1)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
connection_test_result= sock.connect_ex((ip, int(port)))
return connection_test_result
推荐阅读
- sql - 如果 SQL Server 中的主键匹配,则约束更新值
- java - 无法看到提供提示或重定向到错误路径的失败构建的 java 编译器行
- javascript - 微型 mce 编辑器不适用于 https url
- jwt - 创建基于ip地址的JWT认证
- java - 如何正确连接 SQLite 与 JavaFX 中的文本字段和标签?
- c++ - 类中未声明的字符串标识符
- mysql - Laravel:加入多个选择语句
- puppet - Puppet、Puppet Master 和 Puppet Server 的区别
- xamarin - 有没有办法在 Xamarin.Forms 中实现 Stripe 卡小部件?
- python - Tweepy 转推机器人不断循环