1 import paramiko 2 import sys 3 4 5 user = "root" 6 pwd = "123456" 7 8 9 10 # 上传文件 11 def sftp_upload_file(server_path, local_path): 12 try: 13 t = paramiko.Transport((ip, 22)) 14 t.connect(username=user, password=pwd) 15 sftp = paramiko.SFTPClient.from_transport(t) 16 sftp.put(local_path, server_path) 17 t.close() 18 except Exception as e: 19 print(e) 20 21 # 下载文件 22 def sftp_down_file(server_path, local_path): 23 try: 24 t = paramiko.Transport((ip, 22)) 25 t.connect(username=user, password=pwd) 26 sftp = paramiko.SFTPClient.from_transport(t) 27 sftp.get(server_path, local_path) 28 t.close() 29 except Exception as e: 30 print(e) 31 32 # 连接 33 def ssh_conn(ip, cmd): 34 35 ssh = paramiko.SSHClient() 36 # 允许连接不在known_hosts文件上的主机 37 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 38 # 连接服务器 39 ssh.connect(ip, 22, user, pwd) 40 # 执行命令 41 stdin, stdout, stderr = ssh.exec_command(cmd) 42 # 获取结果 43 print(10 * "-", 'start', 10 * "-") 44 for line in stdout: 45 res=(line.strip(' ').split()) 46 print(res) 47 else: 48 print(stdout) 49 print(10 * "-", 'end', 10 * "-") 50 51 def menu(): 52 print(''' 53 * - - - - - - - - - - - - - - - - - * 54 菜单 55 1>上传文件 56 2>下载文件 57 3>执行命令 58 4>退出 59 * - - - - - - - - - - - - - - - - - * 60 ''') 61 62 choice = int(input('请输入你要执行的操作: ')) 63 if choice == 1: 64 src = input('请输入原路径: ') 65 dest = input('请输入目标路径: ') 66 sftp_upload_file(src, dest) 67 elif choice == 2: 68 src = input('请输入原路径: ') 69 dest = input('请输入目标路径: ') 70 sftp_down_file(src, dest) 71 elif choice == 3: 72 while True: 73 cmd = input('请输入要执行的命令: ') 74 if cmd == 'eixt': 75 sys.exit() 76 ssh_conn(ip, cmd) 77 else: 78 sys.exit() 79 80 81 if __name__ == '__main__': 82 ip = input('请输入目标ip: ') 83 while True: 84 menu()