使用Python ftplib庫進行封裝FTP自動下載

小小滴人a發表於2024-10-23
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")

相關文章