我编写了一个简单的 python pexpect 脚本来 ssh 进入机器并执行操作。现在我需要对多台服务器执行此操作。我正在使用一个列表来同时使用多线程访问所有服务器。我的问题是由于所有内容都同时运行,每个线程都在相同的服务器名称上运行。有没有办法同时让每个线程只运行列出的服务器之一?
#! /usr/bin/python
#Test script
import pexpect
import pxssh
import threading
import datetime
currentdate = datetime.datetime.now()
easterndate = (datetime.datetime.now() + datetime.timedelta(0, 3600))
#list of servers
serverlist = ["025", "089"]
#server number
sn = 0
ssh_new_conn = 'Are you sure you want to continue connecting'
class ThreadClass(threading.Thread):
def run(self):
index = 0
sn = serverlist[index]
print sn
username = '[a username]'
password = '[a password]'
hostname = '%(sn)s.[the rest of the host url]' % locals()
command = "/usr/bin/ssh %(username)s@%(hostname)s " % locals()
index = index + 1
now = datetime.datetime.now()
print command
p = pexpect.spawn(command, timeout=360)
***do some other stuff****
for i in range(len(severlist)):
t = ThreadClass()
t.start()
[更新]我可能只是尝试使用调用子线程的父线程等来执行此操作....尽管如果多线程可以从列表或某种工作队列中工作会很好。