使用paramiko进行ssh连接,同时threading进行多线程处理
threads = []
for item in array:
t = threading.Thread(target = self.verifySingle_account, args = (allSshInfo, username, password, port, item))
threads.append(t)
for thr in threads:
thr.start()
for thr in threads:
"""
isAlive()方法可以返回True或False,用来判断是否还有没有运行结束
的线程。如果有的话就让主线程等待线程结束之后最后再结束。
"""
if thr.isAlive():
thr.join()
def verifySingle_account(self, allInfo, username, password, port, item):
try:
#创建一个ssh的客户端,用来连接服务器
ssh = paramiko.SSHClient()
#创建一个ssh的白名单
know_host = paramiko.AutoAddPolicy()
#加载创建的白名单
ssh.set_missing_host_key_policy(know_host)
ssh.connect(
hostname = item["name"],
port = port,
username = username,
password = password,
timeout = 5
)
except Exception as e:
else:
ssh.close()
ssh连接后 进行执行命令。
同时此处有个问题,命令执行结束但未发生错误时,stdout不能进行read()或readlines,可能会一直卡住,因为程序认为没有执行完,会一直进行等待读取后续的,但是其实后续已经没有了,所以等到超时会直接报错,
所以在此处我进行了stdout的readline,如果找到成功时的输出便便关闭连接,处理下面的程序。
stdin, stdout, stderr = ssh.exec_command(deploy_command)
out = ''
is_success = False
while True:
temp = stdout.readline()
if not temp:
break
out = out + temp
if (out.find('成功时的输出') != -1):
ssh.close()
is_success = True
err = stderr.read()
ssh.close()