from ftplib import FTP
from baseapi.logger import MyLogger
logger = MyLogger.get_logger()
class FTPUtils:
ftp = FTP()
ftp.set_pasv(False)
def __init__(self, username, password, host, port=21):
"""
用于FTP站点初始化
:param username: FTP用户名
:param password: FTP密码
:param host: FTP站点地址
:param port: FTP站点端口
"""
self.ftp.connect(host, port, timeout=30)
self.ftp.login(username, password)
logger.info("FTP init success")
def remote_file_exists(self, remote_file, remote_path):
"""
用于FTP站点目标文件存在检测
:param remote_file: 目标文件名
:param remote_path: 目标路径
:return: True/False
"""
self.ftp.cwd(remote_path) # 进入目标目录
remote_file_names = self.ftp.nlst() # 获取文件列表
if remote_file in remote_file_names:
logger.info(f"{remote_file} exists in {remote_path}")
return True
else:
logger.info(f"{remote_file} exists not in {remote_path}")
return False
def download_file(self, local_file, remote_file):
"""
用于目标文件下载
:param local_file: 本地文件名
:param remote_file: 远程文件名
"""
logger.info(f"Download {remote_file} to {local_file}")
with open(local_file, 'wb') as fp:
self.ftp.retrbinary(f'RETR {remote_file}', fp.write)
def quit_ftp(self):
"""
用于FTP退出
"""
self.ftp.quit()
logger.info("FTP quit success")
标签:ftplib,remote,FTP,Python,self,param,file,ftp
From: https://www.cnblogs.com/xxiaow/p/18496368