最近公司需要使用SFTP进行文件的传输,试着用Python实现了一下,主要用到的模块是paramiko。该模块详细的文档可以参考下面的网址内容:http://www.paramiko.org/
主要实现的功能:
需要注意的关键点:
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 14 11:47:55 2016
@author: Neil
Test for Sftp
"""
import paramiko
import sys
import time
import os
class 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的下载,还可以实现未正确下载的文件再次下载,直到所有文件全部下载完毕,有兴趣的小伙伴可以实现一下^-^