import paramiko import sys user = "root" pwd = "123456" # 上傳文件 def sftp_upload_file(server_path, local_path): try: t = paramiko.Transport((ip, 22)) t.connect(username=user, password=pwd) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(local_path, server_path) t.close() except Exception as e: print(e) # 下載文件 def sftp_down_file(server_path, local_path): try: t = paramiko.Transport((ip, 22)) t.connect(username=user, password=pwd) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(server_path, local_path) t.close() except Exception as e: print(e) # 連接 def ssh_conn(ip, cmd): ssh = paramiko.SSHClient() # 允許連接不在known_hosts文件上的主機 ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 連接服務器 ssh.connect(ip, 22, user, pwd) # 執行命令 stdin, stdout, stderr = ssh.exec_command(cmd) # 獲取結果 print(10 * "-", 'start', 10 * "-") for line in stdout: res=(line.strip('\n').split()) print(res) else: print(stdout) print(10 * "-", 'end', 10 * "-") def menu(): print(''' * - - - - - - - - - - - - - - - - - * 菜單 1>上傳文件 2>下載文件 3>執行命令 4>退出 * - - - - - - - - - - - - - - - - - * ''') choice = int(input('請輸入你要執行的操作:\n')) if choice == 1: src = input('請輸入原路徑:\n') dest = input('請輸入目標路徑:\n') sftp_upload_file(src, dest) elif choice == 2: src = input('請輸入原路徑:\n') dest = input('請輸入目標路徑:\n') sftp_down_file(src, dest) elif choice == 3: while True: cmd = input('請輸入要執行的命令:\n') if cmd == 'eixt': sys.exit() ssh_conn(ip, cmd) else: sys.exit() if __name__ == '__main__': ip = input('請輸入目標ip:\n') while True: menu()