import paramiko import threading class ftpclient(object): def __init__(self): self.ssh = paramiko.SSHClient() def sftp_connect(self, hostname, port, username, passwd): transprot = paramiko.Transport((hostname, port)) transprot.connect(username=username, password=passwd) self.sftp = paramiko.SFTPClient.from_transport(transprot) def ssh_connect(self, hostname, port, username, passwd): self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.ssh.connect(hostname=hostname, port=port, username=username, password=passwd) def cmd_ssh(self, *args): while True: cmd = input(">>>") if cmd == 'q': exit() stin, stdout, stderr = self.ssh.exec_command(cmd) res, err = stdout.read(), stderr.read() result = res if res else err print(result.decode()) def interactive(self): while True: cmd = input(">>>").strip() if not cmd: continue if cmd == 'q': exit() cmd_str = cmd.split()[0] if hasattr(self, "%s" % cmd_str): #判斷用戶輸入的命令是否存在 func = getattr(self, "%s" % cmd_str) # 若是self對象中有屬性cmd_str則打印cmd_str的值 func(cmd) def get(self, *args): filename = args[0].split()[1] self.sftp.put(filename, filename) host_list = ['192.168.15.94', '192.168.15.210'] host_action = ["Action", "Put"] def login(): while True: port = input("請輸入端口>>>").strip() if port.isdigit(): port = int(port) else: continue username = input("請輸入用戶名>>>").strip() if not username: print("用戶爲空") continue elif username.isdigit(): print("無數字開頭用戶") continue passwd = input("請輸入密碼>>>").strip() if not passwd: print("密碼爲空") continue return [port, username, passwd] #轉爲一個列表 def main(): while True: for index, host in enumerate(host_list): print(index, host) choice_host = input("請輸入你要進去的主機列表>>>").strip() if choice_host.isdigit() and int(choice_host) < len(host_list): choice_host = int(choice_host) print('\033[41;1m %s \033[0m' % (host_list[choice_host])) print("\t") else: continue for index2, host2 in enumerate(host_action): print(index2, host2) choice_host_action = input("請輸入你作的操做>>>").strip() if choice_host_action.isdigit() and int(choice_host_action) < len(host_action): choice_host_action = int(choice_host_action) print('\033[41;1m %s \033[0m' % (host_action[choice_host_action])) print("\t") hostname = host_list[int(choice_host)] if choice_host_action == 0: while True: connect_list = login() port = connect_list[0] username = connect_list[1] passwd = connect_list[2] try: ftp = ftpclient() ftp.ssh_connect(hostname, port, username, passwd) ftp.cmd_ssh() except ImportError as e: print("有錯誤") elif choice_host_action == 1: while True: connect_list = login() port = connect_list[0] username = connect_list[1] passwd = connect_list[2] try: sftp = ftpclient() sftp.ssh_connect(hostname, port, username, passwd) sftp.cmd_ssh() except ImportError as e: print("有錯誤") else: print("沒有這個編號!!") p = threading.Thread(target=main,args=()) p.start()