Python使用sftp實現(xiàn)上傳和下載功能
在Python中可以使用paramiko模塊中的sftp登陸遠程主機,實現(xiàn)上傳和下載功能。
1.功能實現(xiàn)1、根據(jù)輸入?yún)?shù)判斷是文件還是目錄,進行上傳和下載2、本地參數(shù)local需要與遠程參數(shù)remote類型一致,文件以文件名結(jié)尾,目錄以結(jié)尾3、上傳和下載的本地和遠程目錄需要存在4、異常捕獲
2.代碼實現(xiàn)#!/usr/bin/python# coding=utf-8import paramikoimport osdef sftp_upload(host,port,username,password,local,remote): sf = paramiko.Transport((host,port)) sf.connect(username = username,password = password) sftp = paramiko.SFTPClient.from_transport(sf) try:if os.path.isdir(local):#判斷本地參數(shù)是目錄還是文件 for f in os.listdir(local):#遍歷本地目錄sftp.put(os.path.join(local+f),os.path.join(remote+f))#上傳目錄中的文件else: sftp.put(local,remote)#上傳文件 except Exception,e:print(’upload exception:’,e) sf.close()def sftp_download(host,port,username,password,local,remote): sf = paramiko.Transport((host,port)) sf.connect(username = username,password = password) sftp = paramiko.SFTPClient.from_transport(sf) try:if os.path.isdir(local):#判斷本地參數(shù)是目錄還是文件 for f in sftp.listdir(remote):#遍歷遠程目錄 sftp.get(os.path.join(remote+f),os.path.join(local+f))#下載目錄中文件else: sftp.get(remote,local)#下載文件 except Exception,e:print(’download exception:’,e) sf.close()if __name__ == ’__main__’: host = ’192.168.1.2’#主機 port = 22 #端口 username = ’root’ #用戶名 password = ’123456’ #密碼 local = ’F:sftptest’#本地文件或目錄,與遠程一致,當前為windows目錄格式,window目錄中間需要使用雙斜線 remote = ’/opt/tianpy5/python/test/’#遠程文件或目錄,與本地一致,當前為linux目錄格式 sftp_upload(host,port,username,password,local,remote)#上傳 #sftp_download(host,port,username,password,local,remote)#下載3.總結(jié)
以上代碼實現(xiàn)了文件和目錄的上傳和下載,可以單獨上傳和下載文件,也可以批量上傳和下載目錄中的文件,基本實現(xiàn)了所要的功能,但是針對目錄不存在的情況,以及上傳和下載到多臺主機上的情況,還有待完善。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網(wǎng)。
相關(guān)文章:
1. ASP中格式化時間短日期補0變兩位長日期的方法2. 解析原生JS getComputedStyle3. PHP循環(huán)與分支知識點梳理4. ASP基礎(chǔ)入門第八篇(ASP內(nèi)建對象Application和Session)5. ASP刪除img標簽的style屬性只保留src的正則函數(shù)6. 小技巧處理div內(nèi)容溢出7. jsp實現(xiàn)登錄驗證的過濾器8. 概述IE和SQL2k開發(fā)一個XML聊天程序9. 怎樣才能用js生成xmldom對象,并且在firefox中也實現(xiàn)xml數(shù)據(jù)島?10. msxml3.dll 錯誤 800c0019 系統(tǒng)錯誤:-2146697191解決方法
