"""
FTP文件下载操作
"""
from ftplib import FTP
import os
class FTP_OP(object):
def __init__(self, host, username, password, port):
"""
初始化ftp
:param host: ftp主机ip
:param username: ftp用户名
:param password: ftp密码
:param port: ftp端口 (默认21)
"""
self.host = host
self.username = username
self.password = password
self.port = port
def ftp_connect(self):
"""
连接ftp
:return:
"""
ftp = FTP()
ftp.set_debuglevel(1)
ftp.connect(host=self.host, port=self.port)
ftp.login(self.username, self.password)
ftp.set_pasv(False)
return ftp
def download_file(self, ftp_file_path, dst_file_path):
"""
从ftp下载文件到本地
:param ftp_file_path: ftp下载文件路径
:param dst_file_path: 本地存放路径
:return:
"""
buffer_size = 204800
ftp = self.ftp_connect()
print(ftp.getwelcome() )
file_list = ftp.nlst(ftp_file_path)
print(file_list)
for file_name in file_list:
print("file_name:"+file_name)
ftp_file = os.path.join(ftp_file_path, file_name)
print("ftp_file:"+ftp_file)
write_file = dst_file_path
print("write_file:"+write_file)
f = open(write_file, "wb")
ftp.retrbinary('RETR %s'%ftp_file, f.write, buffer_size)
ftp.quit()
if __name__ == '__main__':
host = "127.0.0.1"
username = "zcz"
password = "xx"
port = 21
ftp_file_path = "/test/test.xls"
dst_file_path = "D://1.xls"
ftp = FTP_OP(host=host, username=username, password=password, port=port)
ftp.download_file(ftp_file_path=ftp_file_path, dst_file_path=dst_file_path)