[英]Connect to multiple machines with threading in Python
I need to connect to multiple machines and execute set of commands on them. 我需要连接到多台计算机并在它们上执行命令集。 I want to implement this with threading but not sure how I can achieve this. 我想用线程来实现这一点,但不确定如何实现。 Following is the code: 以下是代码:
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()
'''
Can someone help me in achieving this with threading? 有人可以通过线程帮助我实现这一目标吗?
It sounds like you're trying to re-invent Ansible or Salt . 听起来您正在尝试重新发明Ansible或Salt 。 You might wish to investigate using one of these tools to accomplish your goal of running a set of shell commands on many machines. 您可能希望研究使用这些工具之一来实现在多台机器上运行一组Shell命令的目标。 Both happen to be written in, and are extensible with, Python. 两者都是用Python编写的,并且可以用Python扩展。
Assuming the function conn_to_board(board_ip)
already does what you want and does not bind the same local port or exclusivelu uses a resource, multithreading is simple and your code is almost correct. 假设函数conn_to_board(board_ip)
已经满足您的要求,并且没有绑定相同的本地端口,或者独占使用资源,那么多线程很简单,并且您的代码几乎是正确的。 The only problem I can see in your commented code is that you join each thread inside the loop actually serializing them one after the other - said differently the multi-threading is completely useless here. 我在注释代码中看到的唯一问题是,您实际上将循环中的每个线程都一个接一个地序列化地加入了循环中-换句话说,多线程在这里是完全没有用的。
You should first create and start all your threads (if the number is low enough) and then join them in a new loop: 您应该首先创建并启动所有线程(如果数量足够少),然后将它们加入新的循环中:
...
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.