Python通过SSH下载远程服务器文件
生活随笔
收集整理的這篇文章主要介紹了
Python通过SSH下载远程服务器文件
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
Python通過SSH下載遠程服務器文件
- 1.安裝SSH登錄三方庫paramiko
- 2.運行下載腳本
有些遠程服務器只能通過SSH登錄,不能通過Samba將文件下載到本地形,可以通過下面腳本批量下載指定文件夾里面所有文件到本地,下載的原理是模擬用戶輸入ls 和 cat兩個指令,將cat讀取到的信息保存本地文件
1.安裝SSH登錄三方庫paramiko
使用pip install paramiko 安裝
2.運行下載腳本
import paramiko,os,sysinput_dir = "/home/" #需要下載遠程服務器的目標文件夾路徑 output_dir = """E:\AndroidProject\save_file""" #要保存文件的路徑 hostname = 'XXX.XXX.X.XXX' #服務器IP地址 username = 'XXXX' # 登錄賬號 password = 'XXXX' #登錄密碼 port = 22def list_dir(root):cmd = 'ls --file-type '+rootstdin, stdout, stderr = ssh.exec_command(cmd)result = stdout.read()return result.decode().split('\n')def save_file(root,name):try:save_path = output_dir + root.split(input_dir)[-1]if not os.path.exists(save_path):os.makedirs(save_path)save_file_path = save_path + namecmd = 'cat '+ root + namestdin, stdout, stderr = ssh.exec_command(cmd)result = stdout.read()if not result:returnwith open(save_file_path,'wb+') as fd:fd.write(result)print('save file:'+save_file_path)except :print('save path:'+save_file_path)print("Unexpected error:", sys.exc_info()[0])def traverse_dir(root):nodes = list(item for item in list_dir(root) if len(item) > 0)for node in nodes:#如果該節點是文件夾,繼續遍歷if node.endswith('/'):traverse_dir(root + node)else:#如果該節點是文件 則保存該文件save_file(root,node)if __name__ == '__main__':if len(output_dir) > 0 and output_dir[-1] != '/':output_dir += '/'if len(input_dir) > 0 and input_dir[-1] != '/':input_dir += '/'ssh = paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())ssh.connect(hostname=hostname, port=port, username=username, password=password)traverse_dir(input_dir)ssh.close()總結
以上是生活随笔為你收集整理的Python通过SSH下载远程服务器文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 解决Unity3D导出apk失败:Fai
- 下一篇: ASCII码字符对照表