如何用脚本同步FTP到本地?

wen 实用脚本 2

本文目录导读:

如何用脚本同步FTP到本地?

  1. Linux/macOS 使用 lftp 脚本
  2. 使用 rsync + curlftpfs (推荐)
  3. Windows PowerShell 脚本
  4. Python 脚本 (跨平台)
  5. 定时同步 (cron任务)
  6. 使用建议

我可以为您提供几种同步FTP到本地的脚本方案,根据您的操作系统和需求选择:

Linux/macOS 使用 lftp 脚本

安装 lftp

# Ubuntu/Debian
sudo apt-get install lftp
# macOS
brew install lftp

同步脚本 (sync_ftp.sh)

#!/bin/bash
# FTP配置
FTP_HOST="ftp.example.com"
FTP_USER="username"
FTP_PASS="password"
FTP_PORT=21
REMOTE_DIR="/remote/path"
LOCAL_DIR="/local/path"
# 使用lftp同步
lftp -u "$FTP_USER:$FTP_PASS" -e "
set ftp:passive-mode true;
set ssl:verify-certificate no;
mirror --continue --delete --verbose \
       --exclude-glob '*.tmp' \
       --exclude-glob '*.log' \
       "$REMOTE_DIR" "$LOCAL_DIR";
quit
" $FTP_HOST

使用 rsync + curlftpfs (推荐)

安装 curlftpfs

sudo apt-get install curlftpfs

挂载FTP并同步

#!/bin/bash
MOUNT_POINT="/mnt/ftp"
LOCAL_DIR="/local/sync"
# 挂载FTP
mkdir -p $MOUNT_POINT
curlftpfs ftp://username:password@ftp.example.com $MOUNT_POINT
# 使用rsync同步
rsync -avz --delete \
      --exclude='*.tmp' \
      $MOUNT_POINT/remote/path/ \
      $LOCAL_DIR/
# 卸载FTP
fusermount -u $MOUNT_POINT

Windows PowerShell 脚本

# sync_ftp.ps1
$FTPHost = "ftp.example.com"
$FTPUser = "username"
$FTPPass = "password"
$RemotePath = "/remote/path/"
$LocalPath = "C:\local\sync"
# 创建FTP连接
$FTPRequest = [System.Net.FtpWebRequest]::Create("ftp://$FTPHost$RemotePath")
$FTPRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectory
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($FTPUser, $FTPPass)
$Response = $FTPRequest.GetResponse()
$Stream = $Response.GetResponseStream()
$Reader = New-Object System.IO.StreamReader($Stream)
$Files = $Reader.ReadToEnd().Split("`r`n")
# 下载每个文件
foreach ($File in $Files) {
    if ($File -ne "") {
        $RemoteFile = "ftp://$FTPHost$RemotePath$File"
        $LocalFile = Join-Path $LocalPath $File
        $DownloadRequest = [System.Net.FtpWebRequest]::Create($RemoteFile)
        $DownloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
        $DownloadRequest.Credentials = New-Object System.Net.NetworkCredential($FTPUser, $FTPPass)
        $DownloadResponse = $DownloadRequest.GetResponse()
        $DownloadStream = $DownloadResponse.GetResponseStream()
        # 创建本地文件夹
        $LocalDir = Split-Path $LocalFile -Parent
        if (!(Test-Path $LocalDir)) {
            New-Item -ItemType Directory -Force -Path $LocalDir
        }
        # 下载文件
        $FileStream = New-Object System.IO.FileStream($LocalFile, [System.IO.FileMode]::Create)
        $DownloadStream.CopyTo($FileStream)
        $FileStream.Close()
        $DownloadStream.Close()
        $DownloadResponse.Close()
    }
}
$Reader.Close()
$Stream.Close()
$Response.Close()

Python 脚本 (跨平台)

# sync_ftp.py
import ftplib
import os
from pathlib import Path
def sync_ftp(host, username, password, remote_dir, local_dir, port=21):
    # 连接FTP
    ftp = ftplib.FTP()
    ftp.connect(host, port)
    ftp.login(username, password)
    ftp.cwd(remote_dir)
    # 获取文件列表
    files = []
    ftp.retrlines('LIST', files.append)
    # 创建本地目录
    Path(local_dir).mkdir(parents=True, exist_ok=True)
    # 下载文件
    for file_info in files:
        parts = file_info.split()
        if len(parts) > 8:
            filename = parts[-1]
            if filename not in ['.', '..']:
                local_path = os.path.join(local_dir, filename)
                with open(local_path, 'wb') as f:
                    ftp.retrbinary(f'RETR {filename}', f.write)
                print(f"Downloaded: {filename}")
    ftp.quit()
# 使用示例
if __name__ == "__main__":
    sync_ftp(
        host="ftp.example.com",
        username="user",
        password="pass",
        remote_dir="/remote/path",
        local_dir="/local/path"
    )

定时同步 (cron任务)

Linux crontab 设置

# 编辑crontab
crontab -e
# 每天凌晨2点同步
0 2 * * * /path/to/sync_ftp.sh >> /var/log/ftp_sync.log 2>&1
# 每30分钟同步
*/30 * * * * /path/to/sync_ftp.sh

使用建议

  1. 选择方案

    • Linux/macOS:推荐 lftp 或 rsync+curlftpfs
    • Windows:推荐PowerShell或Python脚本
    • 跨平台:Python脚本最通用
  2. 安全考虑

    • 不要在脚本中硬编码密码,使用环境变量
    • FTP_PASS="${FTP_PASSWORD}"
    • 考虑使用SSH密钥或FTPES加密连接
  3. 日志记录

    # 添加日志
    LOG_FILE="sync_$(date +%Y%m%d).log"
    lftp ... >> $LOG_FILE 2>&1

您需要哪种系统的具体实现?我可以为您提供更详细的配置。

抱歉,评论功能暂时关闭!