importsettingsimportparamiko,threadingclassOperate_Remote_Host(object):def __init__(self,host,port,username,password,cmd):
self.host=host
self.port=port
self.username=username
self.password=password
self.cmd=cmddefrun(self):
str_cmd=self.cmd.split()[0]ifhasattr(self,str_cmd):
getattr(self, str_cmd)()else:setattr(self,str_cmd,self.command)
getattr(self,str_cmd)()defcommand(self):
ssh=paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy)
ssh.connect(hostname=self.host, port=self.port, username=self.username, password=self.password)
stdin, stdout, stderr=ssh.exec_command(self.cmd)
res, err=stdout.read(), stderr.read()
result= res if res elseerrprint(result.decode())
ssh.close()defput(self):
src_file= self.cmd.split()[1]
dest_file= self.cmd.split()[2]
transport=paramiko.Transport(self.host, self.port)
transport.connect(username=self.username, password=self.password)
sftp=paramiko.SFTPClient.from_transport(transport)
sftp.put(src_file,dest_file)
transport.close()defget(self):
src_file= self.cmd.split()[1]
dest_file= self.cmd.split()[2]
transport=paramiko.Transport(self.host, self.port)
transport.connect(username=self.username, password=self.password)
sftp=paramiko.SFTPClient.from_transport(transport)
sftp.get(src_file,dest_file)
transport.close()defshow_host_list():for key insettings.host_dict.keys():print("环境类型:%s 主机数:%d" %(key, len(settings.host_dict[key])))whileTrue:"""通过选择分组显示主机名与IP"""choose_env=input("请输入操作的环境>>>:").strip()if choose_env insettings.host_dict.keys():
host_show=settings.host_dict[choose_env]for host inhost_show.keys():print("IP:%s hostname:%s"%(host_show[host]['IP'],host_show[host]['hostname']))returnhost_showelse:print("NO exit this env!")defmain(choose_host_dict):
thread_list=[]whileTrue:
cmd=input("请输入命令>>>").strip()ifcmd:for host inchoose_host_dict:
host,port,username,password=choose_host_dict[host]['IP'],choose_host_dict[host]['port'],choose_host_dict[host]['user'],choose_host_dict[host]['password']
func=Operate_Remote_Host(host,port,username,password,cmd)
t= threading.Thread(target=func.run)
t.start()
thread_list.append(t)for t inthread_list:
t.join()else:continue
defrun():
choose_host_dict=show_host_list()
main(choose_host_dict)