萬盛學電腦網

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

Python ftplib 實現 FTP 客戶端:上傳下載、目錄操作、斷點續傳完整實戰

ftplib 核心能力

Python 標準庫 ftplib 提供完整的 FTP 協議客戶端實現,支援主動/被動模式、二進制/文本傳輸、目錄操作、斷點續傳,無需第三方依賴。

基礎連接與認證


from ftplib import FTP
import ftplib

def create_ftp_client(host, port=21, user='anonymous', passwd='', passive=True, timeout=30):
    ftp = FTP()
    ftp.set_debuglevel(0)  # 2=顯示詳細協議交互
    ftp.connect(host, port, timeout=timeout)
    ftp.login(user, passwd)
    ftp.set_pasv(passive)  # True=被動模式(穿透防火牆), False=主動模式
    return ftp

文件上傳下載

二進制模式 (推薦,適用所有文件)


def upload_file(ftp, local_path, remote_path, blocksize=8192):
    with open(local_path, 'rb') as f:
        ftp.storbinary(f'STOR {remote_path}', f, blocksize=blocksize)

def download_file(ftp, remote_path, local_path, blocksize=8192):
    with open(local_path, 'wb') as f:
        ftp.retrbinary(f'RETR {remote_path}', f.write, blocksize=blocksize)

文本模式 (僅適用文本文件,自動行尾轉換)


def upload_text(ftp, local_path, remote_path):
    with open(local_path, 'r', encoding='utf-8') as f:
        ftp.storlines(f'STOR {remote_path}', f)

def download_text(ftp, remote_path, local_path):
    with open(local_path, 'w', encoding='utf-8') as f:
        ftp.retrlines(f'RETR {remote_path}', f.write)

目錄操作


def list_dir(ftp, path='.'):
    """返回目錄條目列表: [(name, facts), ...]"""
    ftp.cwd(path)
    return ftp.mlsd()  # 機器可解析格式 (RFC 3659)

def make_dir(ftp, path):
    try:
        ftp.mkd(path)
    except ftplib.error_perm as e:
        if not e.args[0].startswith('550'):  # 忽略目錄已存在
            raise

def remove_dir(ftp, path):
    ftp.rmd(path)

def delete_file(ftp, path):
    ftp.delete(path)

def rename(ftp, from_name, to_name):
    ftp.rename(from_name, to_name)

斷點續傳核心實現


import os

def download_resume(ftp, remote_path, local_path, blocksize=8192):
    """支援斷點續傳下載"""
    local_size = os.path.getsize(local_path) if os.path.exists(local_path) else 0
    
    # 獲取遠程文件大小
    try:
        remote_size = ftp.size(remote_path)
    except ftplib.error_perm:
        raise FileNotFoundError(f"Remote file not found: {remote_path}")
    
    if local_size >= remote_size:
        print("File already complete")
        return
    
    # 設置斷點位置
    ftp.voidcmd(f'REST {local_size}')
    
    mode = 'ab' if local_size > 0 else 'wb'
    with open(local_path, mode) as f:
        ftp.retrbinary(f'RETR {remote_path}', f.write, blocksize=blocksize, rest=local_size)
    
    print(f"Resumed: {local_size} -> {remote_size} bytes")

def upload_resume(ftp, local_path, remote_path, blocksize=8192):
    """支援斷點續傳上傳 (需服務器支援 APPE/REST)"""
    local_size = os.path.getsize(local_path)
    
    # 嘗試獲取遠程已傳輸大小
    try:
        remote_size = ftp.size(remote_path)
    except ftplib.error_perm:
        remote_size = 0
    
    if remote_size >= local_size:
        print("File already complete")
        return
    
    with open(local_path, 'rb') as f:
        f.seek(remote_size)
        ftp.voidcmd(f'REST {remote_size}')
        ftp.storbinary(f'APPE {remote_path}', f, blocksize=blocksize)
    
    print(f"Resumed upload: {remote_size} -> {local_size} bytes")

完整封裝類


class FTPClient:
    def __init__(self, host, port=21, user='anonymous', passwd='', passive=True):
        self.ftp = FTP()
        self.ftp.connect(host, port)
        self.ftp.login(user, passwd)
        self.ftp.set_pasv(passive)
        self.ftp.encoding = 'utf-8'  # Python 3.6+ 支援 UTF-8 路徑
    
    def __enter__(self):
        return self
    
    def __exit__(self, *args):
        self.close()
    
    def close(self):
        try:
            self.ftp.quit()
        except:
            self.ftp.close()
    
    # ... 封裝上述所有方法 ...
    
    def is_directory(self, path):
        """判斷遠程路徑是否為目錄"""
        try:
            self.ftp.cwd(path)
            self.ftp.cwd('..')
            return True
        except ftplib.error_perm:
            return False
    
    def mirror_download(self, remote_dir, local_dir):
        """遞歸下載整個目錄樹"""
        os.makedirs(local_dir, exist_ok=True)
        self.ftp.cwd(remote_dir)
        for name, facts in self.ftp.mlsd():
            remote_path = f"{remote_dir}/{name}"
            local_path = os.path.join(local_dir, name)
            if facts['type'] == 'dir':
                self.mirror_download(remote_path, local_path)
            else:
                self.download_file(remote_path, local_path)
        self.ftp.cwd('..')
    
    def mirror_upload(self, local_dir, remote_dir):
        """遞歸上傳整個目錄樹"""
        self.make_dir(remote_dir)
        self.ftp.cwd(remote_dir)
        for name in os.listdir(local_dir):
            local_path = os.path.join(local_dir, name)
            remote_path = name
            if os.path.isdir(local_path):
                self.mirror_upload(local_path, remote_path)
            else:
                self.upload_file(local_path, remote_path)
        self.ftp.cwd('..')

# 使用示例
with FTPClient('ftp.example.com', user='user', passwd='pass') as ftp:
    ftp.mirror_upload('./local_data', '/remote/backup')
    ftp.mirror_download('/remote/data', './local_backup')

主動/被動模式選擇指南

模式連接發起方適用場景防火牆友好度
主動 (PORT)服務器連接客戶端客戶端有公網 IP差,需開放高端口
被動 (PASV)客戶端連接服務器客戶端在 NAT/防火牆後好,只需開放服務器端口範圍

默認使用被動模式 (set_pasv(True)) 兼容性最佳。

編碼問題處理


# Python 3.6+ 原生支援 UTF-8
ftp.encoding = 'utf-8'

# 舊版本需手動處理
ftp.encoding = 'latin-1'  # 強制 latin-1 讀取原始字節
# 手動解碼: name.encode('latin-1').decode('gbk')  # 中文 FTP 服務器常見

ftplib 功能完整且零依賴,配合斷點續傳與目錄鏡像封裝,即可構建生產級文件傳輸工具。

copyright © 萬盛學電腦網 all rights reserved