萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> 程式語言綜合

Python FTP 文件上傳下載完整實戰指南(ftplib)

標準庫 ftplib 核心能力

Python 內建 `ftplib` 提供完整 FTP 客戶端功能:連接、認證、目錄操作、二進制/文本傳輸、被動/主動模式、TLS/SSL 加密(FTPS)。無需第三方依賴,適合腳本自動化、備份同步、設備固件升級等場景。

基礎上傳下載封裝類


# ftp_client.py
import ftplib
import os
import logging
from contextlib import contextmanager
from typing import Optional, Callable, BinaryIO

logger = logging.getLogger(__name__)

class FTPClient:
    """FTP 客戶端封裝:支持上下文管理、自動重連、進度回調"""
    
    def __init__(
        self,
        host: str,
        port: int = 21,
        user: str = 'anonymous',
        passwd: str = '',
        timeout: int = 30,
        passive: bool = True,
        encoding: str = 'utf-8'
    ):
        self.host = host
        self.port = port
        self.user = user
        self.passwd = passwd
        self.timeout = timeout
        self.passive = passive
        self.encoding = encoding
        self._conn: Optional[ftplib.FTP] = None
    
    def connect(self) -> ftplib.FTP:
        """建立連接並登錄"""
        if self._conn:
            try:
                self._conn.voidcmd('NOOP')  # 測試連接活性
                return self._conn
            except Exception:
                self.close()
        
        self._conn = ftplib.FTP()
        self._conn.encoding = self.encoding
        self._conn.connect(self.host, self.port, timeout=self.timeout)
        self._conn.login(self.user, self.passwd)
        self._conn.set_pasv(self.passive)
        logger.info(f"FTP 連接成功: {self.host}:{self.port} (被動模式={self.passive})")
        return self._conn
    
    def close(self) -> None:
        if self._conn:
            try:
                self._conn.quit()
            except Exception:
                self._conn.close()
            finally:
                self._conn = None
    
    def __enter__(self) -> 'FTPClient':
        self.connect()
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb) -> None:
        self.close()
    
    # ========== 核心傳輸方法 ==========
    
    def upload_file(
        self,
        local_path: str,
        remote_path: Optional[str] = None,
        callback: Optional[Callable[[int], None]] = None,
        block_size: int = 8192
    ) -> None:
        """
        上傳文件(二進制模式)。
        :param local_path: 本地文件路徑
        :param remote_path: 遠程路徑,默認同文件名
        :param callback: 進度回調 callback(bytes_sent)
        :param block_size: 塊大小
        """
        if not os.path.isfile(local_path):
            raise FileNotFoundError(f"本地文件不存在: {local_path}")
        
        remote_path = remote_path or os.path.basename(local_path)
        conn = self.connect()
        
        # 確保遠程目錄存在
        remote_dir = os.path.dirname(remote_path)
        if remote_dir:
            self._ensure_remote_dir(conn, remote_dir)
        
        file_size = os.path.getsize(local_path)
        sent = 0
        
        def _callback(data: bytes):
            nonlocal sent
            sent += len(data)
            if callback:
                callback(sent)
        
        with open(local_path, 'rb') as f:
            conn.storbinary(f'STOR {remote_path}', f, blocksize=block_size, callback=_callback)
        
        logger.info(f"上傳完成: {local_path} -> {remote_path} ({file_size} bytes)")
    
    def download_file(
        self,
        remote_path: str,
        local_path: Optional[str] = None,
        callback: Optional[Callable[[int], None]] = None,
        block_size: int = 8192,
        overwrite: bool = True
    ) -> None:
        """
        下載文件(二進制模式)。
        :param overwrite: 本地文件存在時是否覆蓋
        """
        local_path = local_path or os.path.basename(remote_path)
        conn = self.connect()
        
        if os.path.exists(local_path) and not overwrite:
            raise FileExistsError(f"本地文件已存在: {local_path}")
        
        # 獲取遠程文件大小(用於進度)
        try:
            file_size = conn.size(remote_path)
        except ftplib.error_perm:
            file_size = -1  # 不支持 SIZE 命令
        
        received = 0
        def _callback(data: bytes):
            nonlocal received
            received += len(data)
            if callback:
                callback(received)
        
        # 寫入臨時文件,完成後原子重命名(防止部分下載)
        temp_path = local_path + '.downloading'
        try:
            with open(temp_path, 'wb') as f:
                conn.retrbinary(f'RETR {remote_path}', _callback, blocksize=block_size)
            os.replace(temp_path, local_path)
            logger.info(f"下載完成: {remote_path} -> {local_path} ({received} bytes)")
        except Exception:
            if os.path.exists(temp_path):
                os.unlink(temp_path)
            raise
    
    # ========== 目錄操作輔助 ==========
    
    def _ensure_remote_dir(self, conn: ftplib.FTP, remote_dir: str) -> None:
        """遞歸創建遠程目錄"""
        if remote_dir in ('', '/', '.'):
            return
        parts = remote_dir.strip('/').split('/')
        current = ''
        for part in parts:
            current += '/' + part
            try:
                conn.mkd(current)
                logger.debug(f"創建遠程目錄: {current}")
            except ftplib.error_perm as e:
                if not e.args[0].startswith('550'):  # 目錄已存在以外的錯誤
                    raise
    
    def list_files(self, remote_dir: str = '.') -> list[str]:
        """列出目錄文件(簡易解析)"""
        conn = self.connect()
        files = []
        conn.retrlines(f'LIST {remote_dir}', files.append)
        return files
    
    def delete_file(self, remote_path: str) -> None:
        self.connect().delete(remote_path)
    
    def rename(self, from_path: str, to_path: str) -> None:
        self.connect().rename(from_path, to_path)

# ========== 使用示例 ==========
if __name__ == '__main__':
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
    
    # 配置信息(實際項目建議從環境變量/配置文件讀取)
    FTP_HOST = '192.168.0.1'
    FTP_USER = 'admin'
    FTP_PASS = 'admin'
    
    # 進度回調示例
    def progress(sent: int):
        print(f"\r已傳輸: {sent/1024:.1f} KB", end='', flush=True)
    
    with FTPClient(FTP_HOST, user=FTP_USER, passwd=FTP_PASS) as ftp:
        # 上傳
        ftp.upload_file('local_data.zip', 'backup/data.zip', callback=progress)
        print()
        
        # 下載
        ftp.download_file('backup/data.zip', 'restored_data.zip', callback=progress)
        print()
        
        # 列表
        for entry in ftp.list_files('backup'):
            print(entry)

關鍵最佳實踐總結

  1. 始終使用二進制模式(`storbinary`/`retrbinary`):避免文本模式換行符轉換損壞二進制文件(圖片、壓縮包、可執行文件)。
  2. 被動模式(PASV)為默認:客戶端發起數據連接,穿透防火牆/NAT 能力強。主動模式需服務器連接客戶端高端口,常被阻擋。
  3. 大文件斷點續傳:`ftplib` 原生不支持,需配合 `REST` 命令手動實現(記錄偏移量、`REST offset` 後 `RETR/STOR`)。生產環境建議用 `rsync`/`lftp` 或封裝庫。
  4. 安全性:優先使用 FTPS (FTP over TLS):

from ftplib import FTP_TLS

ftps = FTP_TLS()
ftps.connect(host, port)
ftps.login(user, passwd)
ftps.prot_p()  # 切換到加密數據通道
# 後續操作同 FTP

常見錯誤排查

錯誤現象可能原因解決方案
530 Login incorrect用戶名/密碼錯誤、用戶被禁用核對憑證、檢查 FTP 服務器用戶配置
425 Can't open data connection被動模式端口範圍未在防火牆開放服務器配置 `pasv_min_port`/`pasv_max_port` 並開放防火牆;或嘗試主動模式 `set_pasv(False)`
550 Permission denied無寫入/刪除權限、目錄不存在檢查用戶權限、確保父目錄存在(用 `_ensure_remote_dir`)
timeout網絡不通、防火牆攔截、服務器負載高增加 timeout、檢查網絡、啟用 keepalive

總結

Python `ftplib` 提供了完整、輕量的 FTP 客戶端能力。通過封裝連接復用、上下文管理、進度回調、目錄自建、原子下載、FTPS 加密,即可構建生產可用的文件傳輸模塊。對於複雜場景(斷點續傳、並發傳輸、SFTP),建議改用 `paramiko` (SFTP) 或 `aioftp` (異步 FTP)。

copyright © 萬盛學電腦網 all rights reserved