1. 运行程序列出主机组或者主机列表
2. 选择指定主机或主机组 3. 选择让主机或者主机组执行命令或者向其传输文件(上传/下载) 4. 充分使用多线程或多进程 5. 不同主机的用户名密码、端口可以不同 </br> **测试:** ---------- 可执行命令 可上传下载文件 ----------**备注:** 1.程序运行在bin/start.py 2.模拟的本地目录为db目录,下面有测试文件test 3.(bug)上传下载只能在输入用户的默认目录进行操作
主函数为:
1 #!/usr/bin/env python 2 # coding=utf-8 3 #Author:yang 4 import threading,paramiko,os,sys 5 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 6 db_path = os.path.join(base_dir,'db') 7 host_name = ['192.168.25.129', '192.168.0.2', '192.168.0.3'] 8 host_cmd = ['执行命令', '文件上传下载','返回主机列表'] 9 msg = { '0': 'str_cmd', '1': 'str_sftp','2':'quit'}10 class ssh_client(object):11 def __init__(self,hostname,username,password,port):12 self.ssh = paramiko.SSHClient()13 self.hostname = hostname14 self.port = int(port)15 self.username = username16 self.password = password17 print(self.hostname,self.port,self.username,self.password)18 19 20 def str_cmd(self):21 self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())22 self.ssh.connect(hostname=self.hostname, port=self.port, username=self.username, password=self.password)23 while True:24 cmd = input('请输入命令:')25 if not cmd:26 continue27 if cmd == 'exit':28 exit()29 stdin,stdout,stderr = self.ssh.exec_command(cmd)30 res,err = stdout.read(),stderr.read()31 result = res if res else err32 print(result.decode())33 34 def str_sftp(self):35 transport = paramiko.Transport((self.hostname,self.port))36 transport.connect(username= self.username,password= self.password)37 self.sftp = paramiko.SFTPClient.from_transport(transport)38 while True:39 cmd = input('请使用put/get上传下载:')40 if len(cmd) == 0:41 continue42 elif cmd == 'exit':43 exit()44 cmd_str = cmd.split()[0]45 if cmd_str == 'get':46 filename = cmd.split()[1]47 localfile= os.path.join(db_path,filename)48 self.sftp.get(filename,localfile)49 elif cmd_str == 'put':50 filename = cmd.split()[1]51 localfile = os.path.join(db_path, filename)52 self.sftp.put(localfile, filename)53 else:54 print('命令无效')55 56 57 58 def mains():59 while True:60 for i,v in enumerate(host_name):61 print(i,v)62 host = input('请输入主机编号:')63 if host_name[int(host)]:64 port = input('请输入端口号:')65 username = input('请输入用户名:')66 password = input('请输入密码:')67 hostname = host_name[int(host)]68 cli_obj = ssh_client(hostname,username,password,port)69 while True:70 for i,v in enumerate(host_cmd):71 print(i,v)72 choise_str = input('请输入进行的指令:')73 if host_cmd[int(choise_str)]:74 str = msg[choise_str]75 print(str)76 if str == 'quit':77 break78 elif str == 'str_cmd':79 cli_obj.str_cmd()80 elif str == 'str_sftp':81 cli_obj.str_sftp()82 else:83 print('编号不存在')84 continue85 86 87 else:88 print('编号不存在')89 continue90 91 92 def run():93 t = threading.Thread(target=mains,args=())94 t.start()