首页 > 解决方案 > 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)

我希望得到: 来自可用服务器的响应来自不可用服务器的错误

怎么实现啊各位?

标签: pythonsshremote-accessparallel-ssh

解决方案


在针对主机(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

推荐阅读