使用Python玩转ftplib库:实现ftp文件传输自动化全攻略

大家好!在日常工作中都会使用到ftp功能,用于上传和下载文件等,本章主要介绍Python的标准库ftplib来实现FTP文件传输,帮助我们实现ftp自动化。

一、ftplib库核心函数速查表

1 连接与登录

#非加密传输
from ftplib import FTP
# 创建FTP对象
ftp = FTP()
# 连接服务器,ftp默认端口为21
ftp.connect(host='168.0.0.1', port=21)
# 登录认证,输入正确的用户名和密码
ftp.login(user='your_username', passwd='your_password')
# 操作完成后,安全退出连接
ftp.quit()


#使用FTPS加密连接,加密传输,防止数据泄露。
from ftplib import FTP_TLS
ftps = FTP_TLS('secure.example.com')
ftps.login(user='admin', passwd='secret')
ftps.prot_p() # 启用加密数据通道

说明:通过FTP()创建对象,connect方法指定服务器地址和端口建立连接,login方法输入用户名和密码完成认证,操作结束后用quit方法关闭连接,避免资源浪费。

2 目录操作

# 获取当前所在目录
current_dir = ftp.pwd()
print(f"当前目录: {current_dir}")

# 切换到目标目录
ftp.cwd('/remote/files')

# 在服务器上创建新目录
ftp.mkd('new_folder')

# 删除空目录,注意目录必须为空才能删除成功
ftp.rmd('old_folder')

3 文件上传下载

1)上传文件

# 以二进制模式上传文件,适用于图片、压缩包等非文本文件
with open('local_file.zip', 'rb') as f:
	ftp.storbinary('STOR remote_file.zip', f)

# 以ASCII模式上传文本文件,如txt,log,html,xml等,保证文本格式正确
with open('readme.txt', 'r') as f:
	ftp.storlines('STOR readme.txt', f)

说明:'STOR remote_file.zip'中的STOR是标准化写法,后面跟的是要上传的文件。

2)下载文件

# 以二进制模式下载文件,将服务器文件保存到本地,第二个参事室回调函数
with open('local.zip', 'wb') as f:
	ftp.retrbinary('RETR remote.zip', f.write)

#传输大文件时,合理设置缓冲区大小能提升传输效率:
# 设置缓冲区大小为1MB,可根据实际情况调整
BUFFER_SIZE = 1024 * 1024
# 使用设置好的缓冲区大小下载大文件

with open('large_file.iso', 'wb') as f:
	ftp.retrbinary('RETR large_file.iso', f.write, blocksize=BUFFER_SIZE)

# 以文本模式下载文件,将服务器文件保存到本地
with open('local.txt', 'wb') as f:
	ftp.retrlines('RETR remote.txt', f.write)

说明:'STOR remote_file.zip'中的STOR是标准化写法,后面跟的是要上传的文件。

在实际使用中,下载文本文件时,可能会遇到转换换行符失败的情况,多行的文件下载后变为了一行。

此时可以自己重写回调函数,在每一行末尾加上换行符,如下:

def write(line):
	f.write(line + '\n')

# 以文本模式下载文件,将服务器文件保存到本地 回调函数为自己定义的write函数
with open('local.txt', 'wb') as f:
	ftp.retrlines('RETR remote.txt', write)

4 文件管理

对服务器上的文件进行管理,这些函数能满足你的常见需求:

# 删除远程服务器上的指定文件
ftp.delete('obsolete_file.txt')
# 重命名文件,方便文件整理
ftp.rename('old_name.txt', 'new_name.txt')
# 获取文件大小,了解文件占用空间
size = ftp.size('large_file.iso')
print(f"文件大小: {size} 字节")

5 目录列表

查看服务器目录内容,这几种方式能让你快速获取文件信息:

# 获取简洁的文件列表
files = ftp.nlst()
print("目录内容:", files)

# 获取详细文件列表,直接打印到控制台
ftp.dir()

# 解析详细列表,获取文件名和类型
ftp.mlsd()

高级操作

# 设置编码
ftp.encoding = 'utf-8'

# 设置传输模式
ftp.set_pasv(True)  # 被动模式(推荐)

# 发送自定义命令
response = ftp.sendcmd('HELP')  # 获取服务器支持的命令
print("服务器支持命令:", response)

# 获取文件修改时间
mod_time = ftp.sendcmd('MDTM config.ini')
print(f"最后修改时间: {mod_time[4:]}")
# 设置超时时间
ftp = FTP(timeout=30)
# 异常处理示例,出现登录失败等问题时可添加重试逻辑
try:
	ftp.login(user, passwd)
except ftplib.error_temp as e:
	print(f"登录失败: {e}")

二、实战案例

案例 1:自动备份数据到FTP

import os
from datetime import datetime
from ftplib import FTP

def backup_site(local_dir, ftp_dir):
    # 创建带时间戳的备份目录,方便区分不同时间的备份
    timestamp = datetime.now().strftime("%Y%m%d_%H%M")
    backup_dir = f"{ftp_dir}/backup_{timestamp}"
    
    ftp = FTP('host地址')
    ftp.login('user', 'password')
    
    # 在服务器上创建备份目录
    ftp.mkd(backup_dir)
    ftp.cwd(backup_dir)
    
    # 遍历本地目录,上传所有文件
    for file in os.listdir(local_dir):
        local_path = os.path.join(local_dir, file)
        if os.path.isfile(local_path):
            with open(local_path, 'rb') as f:
                ftp.storbinary(f'STOR {file}', f)
    
    print(f"备份完成至: {backup_dir}")
    ftp.quit()

backup_site('dir1', '/dir2')

案例 2:定时下载日志文件

自动获取服务器日志,便于后续分析和排查问题:

import schedule
import time
from ftplib import FTP

def download_logs():
    ftp = FTP('host地址')
    ftp.login('user', 'password')
    ftp.cwd('/logs')
    
    # 只下载今日日志,精准获取所需数据
    today = time.strftime("%Y%m%d")
    for file in ftp.nlst():
        if today in file:
            with open(file, 'wb') as f:
                ftp.retrbinary(f'RETR {file}', f.write)
    
    ftp.quit()

# 设置每天凌晨00:05执行下载任务
schedule.every().day.at("00:05").do(download_logs)

while True:
    schedule.run_pending()
    time.sleep(60)
原文链接:,转发请注明来源!