功能:下载vsftpd服务器端文件至本地,并删除服务器端文件。
文件: config.py 配置文件 ftpdown.py 主程序
ftpdown.py代码如下
# encoding:utf-8 import os import sys from config import * from ftplib import FTP class FtpDownloadCls: def __init__(self, ftpserver, port, usrname, pwd): self.ftpserver = ftpserver self.port = port self.usrname = usrname self.pwd = pwd self.ftp = self.ftpConnect() def ftpConnect(self): ftp = FTP() try: ftp.connect(self.ftpserver, self.port) ftp.login(self.usrname, self.pwd) except: raise IOError('ftp连接失败!!!') else: print(ftp.getwelcome()) return ftp def downloadFile(self, ftpfile, localfile): bufsize = 1024 with open(localfile, 'wb') as fid: self.ftp.retrbinary('RETR {0}'.format(ftpfile), fid.write, bufsize) return True def downloadFiles(self, ftpath, localpath,downlist,downlen): print('ftp path: {0} local path: {1} '.format(ftpath,localpath)) if not os.path.exists(localpath): os.makedirs(localpath) self.ftp.cwd(ftpath) for file in self.ftp.nlst(): if file.endswith(".zip") and len(downlist) < downlen: try: print ("下载第{0}/{1}个文件:{2} ,状态:".format(len(downlist)+1,downlen,file),end='') self.downloadFile(file,os.path.join(localpath, file)) downlist.append(file) except Exception as err: print (err) else: print ("successful") print (" 下载完成,开始删除服务端文件 ") return True def ftpdelfile(self,downlist): for filedel in downlist: try: print ("删除第{0}/{1}个文件:{2} ,状态:".format(downlist.index(filedel)+1,downlen,filedel),end='') self.ftp.delete(filedel) except Exception as err: print (err) else: print ("successful") def ftpDisConnect(self): self.ftp.close() if __name__ == '__main__': Ftp = FtpDownloadCls(ftpserver, port, usrname, pwd) Ftp.downloadFiles(ftpath, localpath,downlist,downlen) Ftp.ftpdelfile(downlist) Ftp.ftpDisConnect()
config.py代码如下
#ftp服务器参数 ftpserver = '192.168.56.101' port = 21 usrname = 'doufy' pwd = 'doufy' #ftp数据目录 ftpath = '/mnt/ftpdata' #下载至本地目录 localpath = 'D:/11111/' downlist=[] #下载多少压缩包 downlen=3