写一段python代码,使用多线程建立多个SSH连接
时间: 2023-03-06 17:26:50 浏览: 74
以下是使用多线程建立多个SSH连接的Python代码:import threading
import paramikodef ssh_connect(ip, username, password, command):
client = paramiko.SSHClient()
# 设置允许连接不在know_hosts文件中的主机
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
client.connect(ip, username=username, password=password)
# 执行命令
stdin, stdout, stderr = client.exec_command(command)
# 获取命令结果
result = stdout.read()
# 关闭连接
client.close() return resultif __name__ == '__main__':
# 连接的主机列表
ip_list = ['192.168.1.1', '192.168.1.2', '192.168.1.3']
# 用户名
username = 'root'
# 密码
password = '123456'
# 要执行的命令
command = 'ls'
# thread_num为线程数量
thread_num = 3
# 保存线程
threads = [] # 创建线程
for i in range(thread_num):
ip = ip_list[i]
t = threading.Thread(target=ssh_connect, args=(ip, username, password, command))
threads.append(t) # 启动线程
for t in threads:
t.start()
# 等待线程结束
for t in threads:
t.join()