本文目录导读:

- 使用 lftp 脚本(推荐 Linux/Mac)
- 使用 curl 配合 rsync
- Python 脚本(跨平台)
- Windows 批处理脚本
- 使用 inotify(Linux 实时同步)
- Docker 实现
- 使用建议
是的,可以通过脚本自动将本地文件同步到FTP服务器,以下是几种常见的方法:
使用 lftp 脚本(推荐 Linux/Mac)
#!/bin/bash # sync_to_ftp.sh # FTP 服务器配置 FTP_HOST="ftp.example.com" FTP_USER="username" FTP_PASS="password" LOCAL_DIR="/path/to/local/dir" REMOTE_DIR="/path/to/remote/dir" lftp -u $FTP_USER,$FTP_PASS -e " mirror -R --delete --verbose --parallel=5 $LOCAL_DIR $REMOTE_DIR quit " $FTP_HOST
使用 curl 配合 rsync
#!/bin/bash
# 使用 rsync 通过 FTP 同步
lftp -u "$FTP_USER:$FTP_PASS" -e "
mirror -R --delete --verbose --ignore-time --parallel=3 \
--include-glob '*.{txt,php,html,css,js}' \
$LOCAL_DIR $REMOTE_DIR
quit
" $FTP_HOST
Python 脚本(跨平台)
#!/usr/bin/env python3
# sync_to_ftp.py
from ftplib import FTP
import os
import schedule
import time
def upload_file(local_path, remote_path):
with FTP('ftp.example.com') as ftp:
ftp.login('username', 'password')
# 创建远程目录
remote_dir = os.path.dirname(remote_path)
try:
ftp.cwd(remote_dir)
except:
ftp.mkd(remote_dir)
with open(local_path, 'rb') as f:
ftp.storbinary(f'STOR {remote_path}', f)
def sync_directory():
local_dir = '/path/to/local'
remote_dir = '/remote/path'
for root, dirs, files in os.walk(local_dir):
for file in files:
local_path = os.path.join(root, file)
remote_path = os.path.join(remote_dir,
os.path.relpath(local_path, local_dir))
upload_file(local_path, remote_path)
# 定时同步,每小时执行一次
schedule.every().hour.do(sync_directory)
while True:
schedule.run_pending()
time.sleep(60)
Windows 批处理脚本
@echo off :: sync_to_ftp.bat set FTP_HOST=ftp.example.com set FTP_USER=username set FTP_PASS=password set LOCAL_DIR=C:\path\to\local set REMOTE_DIR=/path/to/remote :: 上传文件 echo open %FTP_HOST%> commands.txt echo %FTP_USER%>> commands.txt echo %FTP_PASS%>> commands.txt echo cd %REMOTE_DIR%>> commands.txt echo lcd %LOCAL_DIR%>> commands.txt echo mput *.txt>> commands.txt echo quit>> commands.txt ftp -s:commands.txt del commands.txt
使用 inotify(Linux 实时同步)
#!/bin/bash
# 安装 inotifywait: apt-get install inotify-tools
inotifywait -m -r -e modify,create,delete,move /path/to/local/dir |
while read directory event file; do
lftp -u $FTP_USER,$FTP_PASS -e "
mirror -R --delete --verbose $LOCAL_DIR $REMOTE_DIR
quit
" $FTP_HOST
done
Docker 实现
# docker-compose.yml
version: '3'
services:
ftp-sync:
image: alpine:latest
volumes:
- ./local:/data:ro
- ./snyc.sh:/sync.sh
command: /sync.sh
environment:
- FTP_HOST=ftp.example.com
- FTP_USER=username
- FTP_PASS=password
使用建议
-
安全性:
- 避免在脚本中硬编码密码
- 使用环境变量或加密文件存储凭证
- 考虑使用 SFTP/FTPS 替代明文 FTP
-
定时执行:
# crontab 配置,每小时执行一次 0 * * * * /path/to/sync_to_ftp.sh
-
日志记录:
lftp ... >> /var/log/ftp-sync.log 2>&1
需要根据你的操作系统和具体需求选择合适的方案,建议先从简单的 lftp 或 Python 脚本开始,逐步完善功能。