类 Fabric 主机管理程序开发:
1. 运行程序列出主机组或者主机列表
2. 选择指定主机或主机组
3. 选择让主机或者主机组执行命令或者向其传输文件(上传/下载
4. 充分使用多线程或多进程
5. 不同主机的用户名密码、端口可以不同
代码如下:
#-*-coding:utf-8-*- import threadingimport queue,time,os,paramiko #服务器连接信息获取验证def auth_action(): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) try: db_handle = BASE_DIR+"/db/host.json" except Exception as a: print ("The user is not exist! ",a) print (db_handle) f = open(db_handle) for host_info in f: q.put(host_info) #print (q.qsize())#获取执行命令返回信息;def get_info(hostname,port,username,password,command): ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy) ssh.connect(hostname,port,username,password) # 执行命令; stdin, stdout, stderr = ssh.exec_command(command) result = stdout.read() print("*************", hostname,"*************") print(result.decode()) ssh.close()#上传文件操作;def put_file(hostname,port,username,password): transport = paramiko.Transport((hostname,int(port))) print (hostname,port) transport.connect(username = username, password=password) sftp = paramiko.SFTPClient.from_transport(transport) sftp.put(‘oldboy.avi‘,‘/home/oracle/test_from_win‘) sftp.close()#获取主机列表def get_host_info(): BASE_DIR = os.path.dirname(os.path.dirname(__file__)) try: db_handle = BASE_DIR+"/db/host.json" except Exception as a: print ("The user is not exist! ",a) #print (db_handle) with open (db_handle) as f: print (f.read()) if __name__ =="__main__": q = queue.Queue() msg =""" 1.显示主机列表; 2.主机组执行命令; 3.向主机传输文件; """ while True: print (msg) msg_info = input("请选择要执行的操作:") if msg_info =="1": get_host_info() if msg_info=="2": print (">>>>>") command = input("请输入执行命令!>>>") auth_action() #print (q.qsize()) tmp_list = [] for _ in range(q.qsize()): host_list = q.get().split() hostname, port, username, password = host_list[1], host_list[4], host_list[2], host_list[3] t = threading.Thread(target=get_info, args=((hostname, port, username, password, command))) tmp_list.append(t) t.start() for t in tmp_list: t.join() if msg_info =="3": time_start = time.time() #put_file(hostname, port, username, password) auth_action() tmp_list = [] for _ in range(q.qsize()): host_list = q.get().split() hostname, port, username, password = host_list[1], host_list[4], host_list[2], host_list[3] t = threading.Thread(target=put_file, args=((hostname, port, username, password))) tmp_list.append(t) t.start() for t in tmp_list: t.join() cost_time = time.time() - time_start print ("上传文件已完成,用时:%s" % cost_time) if msg_info =="q": print ("退出系统!") break
时间: 2024-10-15 08:05:49