import os
from datetime import datetime, timedelta
import ftputil
def sync_ftp_to_local(remote_dir, local_dir, ftp_host, ftp_username, ftp_password):
# 连接FTP服务器
ftp = ftputil.FTPHost(ftp_host, ftp_username, ftp_password)
# 获取最近三天的日期
three_days_ago = datetime.now() - timedelta(days=365)
# 遍历远程目录
for root, dirs, files in ftp.walk(remote_dir):
for filename in files:
# 获取文件的完整路径
remote_path = ftp.path.join(root, filename)
# 获取文件的修改时间
modified_time = ftp.path.getmtime(remote_path)
# 检查文件是否是txt扩展名且在最近三天内修改过
if datetime.fromtimestamp(modified_time) > three_days_ago:
# 构建本地目录和文件路径
local_path = os.path.join(local_dir, os.path.relpath(remote_path, remote_dir))
# 创建本地目录
os.makedirs(os.path.dirname(local_path), exist_ok=True)
# 下载文件
ftp.download(remote_path, local_path)
# 关闭FTP连接
ftp.close()
# 示例用法
remote_path = "/root"
local_path = "D:/TestWorkspace/ftp_sync"
ftp_host = "192.168.1.50"
ftp_username = "root"
ftp_password = "password"
sync_ftp_to_local(remote_path, local_path, ftp_host, ftp_username, ftp_password)
import os
import ftputil
from datetime import datetime, timedelta
def sync_ftp_subdirectories_to_local(remote_dir, local_dir):
# 连接FTP服务器
ftp = ftputil.FTPHost('ftp.example.com', 'username', 'password')
# 获取最近三天的日期
three_days_ago = datetime.now() - timedelta(days=3)
# 获取远程目录下的第一层级子目录
subdirectories = ftp.listdir(remote_dir)
# 遍历子目录
for subdir in subdirectories:
# 构建子目录的完整路径
remote_subdir = ftp.path.join(remote_dir, subdir)
# 检查子目录是否存在
if ftp.path.isdir(remote_subdir):
# 遍历子目录下的文件
for filename in ftp.listdir(remote_subdir):
# 获取文件的完整路径
remote_path = ftp.path.join(remote_subdir, filename)
# 获取文件的修改时间
modified_time = ftp.path.getmtime(remote_path)
# 检查文件是否是txt扩展名且在最近三天内修改过
if filename.endswith('.txt') and datetime.fromtimestamp(modified_time) > three_days_ago:
# 构建本地目录和文件路径
local_path = os.path.join(local_dir, subdir, filename)
# 创建本地目录
os.makedirs(os.path.dirname(local_path), exist_ok=True)
# 下载文件
ftp.download(remote_path, local_path)
# 关闭FTP连接
ftp.close()
# 调用函数进行同步
sync_ftp_subdirectories_to_local('/remote/ftp/dir', '/local/dir')