Python的SFTP功能實現
最近公司需要使用SFTP進行檔案的傳輸,試著用Python實現了一下,主要用到的模組是paramiko。該模組詳細的文檔可以參考下面的網址內容:http://www.paramiko.org/ 代碼如下,Python新手,僅供參考嘍:
主要實現的功能: 從指定的SFTP路徑下下載檔案到本地 在本地下載路徑下組建記錄檔檔案,記錄下載內容 檔案下載失敗記錄為下載檔案,跳過該檔案繼續下載
需要注意的關鍵點: get方法只能必須具體到檔案,因此需要對目錄下的所有檔案進行遍曆,然後下載 continue的使用讓下載某個檔案失敗後可以繼續下載
# -*- coding: utf-8 -*-"""Created on Wed Sep 14 11:47:55 2016@author: NeilTest for Sftp"""import paramikoimport sysimport timeimport osclass PySFTP(object): def __init__(self): print('Create a SFTP Deload Project!') def connectSFTP(self,remotename,remoteport,loginname,loginpassword): try: sftp = paramiko.Transport(remotename,remoteport) print('connect success!') except Exception as e: print('connect failed,reasons are as follows:',e) return (0,'connect failed!') else: try: sftp.connect(username = loginname,password = loginpassword) print('login success!') except Exception as e: print('connect failed,reasons are as follows:',e) return (0,'login failed!') else: return (1,sftp) def download(self,remotename,remoteport,loginname,loginpassword,remoteaddress,localaddress): sftp = self.connectSFTP(remotename,remoteport,loginname,loginpassword) if sftp[0] != 1: print(sftp[1]) sys.exit() sftp = paramiko.SFTPClient.from_transport(sftp[1]) filelist = sftp.listdir(remoteaddress) filelist = filelist[:2]#測試時僅下載了2個檔案 print('begin downloading!') for i in filelist: try: start = time.clock() sftp.get(remoteaddress+'/'+i,localaddress+'\\'+i) end = time.clock() print('success download %s,use time %fs' % (i,(end - start))) except Exception as e: print('failed download %s,reason are as follows:' % i,e) with open(r'C:\Users\Neil\Desktop\Test\time.log','a') as f: f.write('failed download %s,reason are as follows:' % i,e) continue #下載出錯繼續進行下一步 else: with open(r'C:\Users\Neil\Desktop\Test\time.log','a') as f: f.write('success download %s\n' % i)def main(): sftp = PySFTP() sftp.download(remotename = 'SFTP的host地址', remoteport=21, #SFTP的預設連接埠號碼是21 loginname = '使用者名稱', loginpassword = '密碼', remoteaddress='下載檔案所在的路徑', localaddress = r'需要下載到的地址路徑') if __name__ == '__main__': main()
其實關於sftp的下載,還可以實現未正確下載的檔案再次下載,直到所有檔案全部下載完畢,有興趣的小夥伴可以實現一下^-^