直接上代码
import os
import sys
from ftplib import FTP
import datetime
class FtpDownloadCls:
def __init__(self, ftpserver, port, usrname, pwd):
self.ftpserver = ftpserver # ftp主机IP
self.port = port # ftp端口
self.usrname = usrname # 登陆用户名
self.pwd = pwd # 登陆密码
self.ftp = self.ftpConnect()
self.ftp.encoding = "utf-8"
# ftp连接
def ftpConnect(self):
ftp = FTP()
try:
ftp.connect(self.ftpserver, self.port)
ftp.login(self.usrname, self.pwd)
except:
raise IOError('\n FTP login failed!!!')
else:
print(ftp.getwelcome())
print('\n+------- FTP connection successful!!! --------+\n')
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):
print('FTP PATH: {0}'.format(ftpath))
if not os.path.exists(localpath):
os.makedirs(localpath)
self.ftp.cwd(ftpath)
print('\n+----------- downloading!!! -----------+\n')
n=-2
for file in self.ftp.nlst():
n=n+1
local = os.path.join(localpath, file)
if os.path.isdir(file): # 判断是否为子目录
pass
else:
if file.find(".") != -1:
print(n,file,datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
self.downloadFile(file,local)
else:
self.downloadFiles(file, local)
self.ftp.cwd('..')
return True
# 退出FTP连接
def ftpDisConnect(self):
self.ftp.quit()
# 程序入口
if __name__ == '__main__':
# 输入参数
ftpserver = 'XXX.XXX.XXX'
port = 21
usrname ='name'
pwd = 'pass'
ftpath = '/Volume_1/'#远程地址
localpath = 'G:\\data\\'#本地地址
Ftp = FtpDownloadCls(ftpserver, port, usrname, pwd)
Ftp.downloadFiles(ftpath, localpath)
Ftp.ftpDisConnect()
print("\n+-------- OK!!! --------+\n")
然后上截图
微信截图_20211228002728.png