在 Python 中使用线程连接到多台机器

Connect to multiple machines with threading in Python

我需要连接到多台机器并在它们上执行一组命令。我想用线程来实现它,但不确定如何实现。 以下是代码:

import threading

def conn_to_board(board_ip):
    # ssh connection to machine
    # set of commands

board_ip = ["1.1.1.1", "2.2.2.2", "3.3.3.3", "4.4.4.4"]

'''
for i in board_ip:
    t1 = threading.Thread(target=conn_to_board, args=(i,))
    t1.start()
    t1.join()
'''

谁能帮我用线程实现这个?

听起来您正在尝试重新发明 Ansible or Salt。您可能希望研究使用这些工具之一来实现在多台机器上 运行 一组 shell 命令的目标。两者都恰好是用 Python.

编写的,并且可以用 Python.

假设函数conn_to_board(board_ip)已经做了你想做的事情并且没有绑定同一个本地端口或者exclusivelu使用资源,多线程很简单并且你的代码几乎是正确的。我在您的注释代码中看到的唯一问题是,您将每个线程加入循环中,实际上是一个接一个地序列化它们——换句话说,多线程在这里完全没用。

您应该首先创建并启动所有线程(如果数量足够少),然后将它们加入一个新循环:

...
thrs = [] # to store the threads
for i in board_ip:  # create and start the threads
    t1 = threading.Thread(target=conn_to_board, args=(i,))
    t1.start()
    thrs.append(t1)
for t1 in thrs:     # join all the threads
    t1.join()