Python3 sftp文件上傳下載以及遠程執行命令
1,簡介
Paramiko模塊是基於Python實現的SSH遠程安全連接,用於SSH遠程執行命令、文件傳輸等功能。
注意:paramiko 2.4.2 依賴 cryptography,而最新的cryptography==2.5里有一些棄用的API。pip install cryptography==2.4.2
2,安裝 paramiko
默認Python沒有自帶,需要手動安裝:
pip install paramiko
3,上傳文件
#!/usr/bin/env python3 # coding: utf-8 import paramiko def sftp_upload_file(host, user, password, server_path, port, local_path, timeout=10): """ 上傳文件,注意:不支持文件夾 :param host: 主機名 :param user: 用戶名 :param password: 密碼 :param server_path: 遠程路徑,比如:/home/test.txt :param local_path: 本地路徑,比如:D:/test.txt :param timeout: 超時時間(默認),必須是int類型 :return: bool """ try: t = paramiko.Transport((host, int(port))) t.banner_timeout = timeout t.connect(username=user, password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.put(local_path, server_path) t.close() return True except Exception as e: print(e) return False, if __name__ == '__main__': host = '192.168.10.1' user = 'root' password = 'root' port = '22' server_path = '/home/test.txt' local_path = 'D:/test.txt' res = sftp_upload_file(host, user, password, port, server_path, local_path) if not res: print("上傳文件: %s 失敗"%local_path) else: print("上傳文件: %s 成功" % local_path)
4,下載文件
#!/usr/bin/env python3 # coding: utf-8 import paramiko def sftp_down_file(host,user,password, port, server_path, local_path,timeout=10): """ 下載文件,注意:不支持文件夾 :param host: 主機名 :param user: 用戶名 :param password: 密碼 :param server_path: 遠程路徑,比如:/home/test.txt :param local_path: 本地路徑,比如:D:/test.txt :param timeout: 超時時間(默認),必須是int類型 :return: bool """ try: t = paramiko.Transport((host,int(port))) t.banner_timeout = timeout t.connect(username=user,password=password) sftp = paramiko.SFTPClient.from_transport(t) sftp.get(server_path, local_path) t.close() return True except Exception as e: print(e) return False if __name__ == '__main__': host = '192.168.10.1' user = 'root' password = 'root' port = '21' server_path = '/home/test.txt' local_path = 'D:/test.txt' res = sftp_down_file(host, user, password, port, server_path, local_path) if not res: print("下載文件: %s 失敗"%server_path) else: print("下載文件: %s 成功" % server_path)
5,遠程執行命令
#!/usr/bin/env python3 # coding: utf-8 import paramiko def ssh_exec_command(host,user,password, cmd,timeout=10): """ 使用ssh連接遠程服務器執行命令 :param host: 主機名 :param user: 用戶名 :param password: 密碼 :param cmd: 執行的命令 :param seconds: 超時時間(默認),必須是int類型 :return: dict """ result = {'status': 1, 'data': None} # 返回結果 try: ssh = paramiko.SSHClient() # 創建一個新的SSHClient實例 ssh.banner_timeout = timeout # 設置host key,如果在"known_hosts"中沒有保存相關的信息, SSHClient 默認行為是拒絕連接, 會提示yes/no ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(host, 22, user, password, timeout=timeout) # 連接遠程服務器,超時時間1秒 stdin, stdout, stderr = ssh.exec_command(cmd,get_pty=True,timeout=timeout) # 執行命令 out = stdout.readlines() # 執行結果,readlines會返回列表 # 執行狀態,0表示成功,1表示失敗 channel = stdout.channel status = channel.recv_exit_status() ssh.close() # 關閉ssh連接 # 修改返回結果 result['status'] = status result['data'] = out return result except Exception as e: print(e) print("錯誤, 登錄服務器或者執行命令超時!!! ip: {} 命令: {}".format(ip,cmd)) return False if __name__ == '__main__': host = '192.168.10.1' user = 'root' password = 'root cmd = "cat /etc/issue | awk '{print $1,$2,$3}'" res = ssh_exec_command(host, user, password, cmd) # print(res) if not res or not res['data'] or res['status'] != 0: print("錯誤, ip: {} 執行命令: {} 失敗".format(host, cmd), "red") exit() value = res['data'][0].strip() # 獲取實際值 print("操作系統為: %s"%value)