繁体   English   中英

使用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()
'''

有人可以通过线程帮助我实现这一目标吗?

听起来您正在尝试重新发明AnsibleSalt 您可能希望研究使用这些工具之一来实现在多台机器上运行一组Shell命令的目标。 两者都是用Python编写的,并且可以用Python扩展。

假设函数conn_to_board(board_ip)已经满足您的要求,并且没有绑定相同的本地端口,或者独占使用资源,那么多线程很简单,并且您的代码几乎是正确的。 我在注释代码中看到的唯一问题是,您实际上将循环中的每个线程都一个接一个地序列化地加入了循环中-换句话说,多线程在这里是完全没有用的。

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

...
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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM