插件窝 干货文章 如何在Linux上设置文件同步

如何在Linux上设置文件同步

同步 lsyncd bash install 102    来源:    2025-04-15

Linux 文件同步方案

在Linux系统上设置文件同步有多种方法,以下是几种常用的解决方案:

1. rsync - 最常用的文件同步工具

基本用法

rsync -avz /source/directory/ user@remote_host:/destination/directory/
  • -a: 归档模式,保留权限、时间戳等
  • -v: 详细输出
  • -z: 压缩传输

定时同步(crontab)

crontab -e
# 添加以下内容,每天凌晨2点同步
0 2 * * * rsync -avz /source/ user@remote:/destination/

排除特定文件

rsync -avz --exclude='*.tmp' --exclude='temp/' /source/ user@remote:/destination/

2. lsyncd - 实时同步工具

安装:

sudo apt install lsyncd  # Debian/Ubuntu
sudo yum install lsyncd  # CentOS/RHEL

配置示例(/etc/lsyncd.conf):

settings {
    logfile = "/var/log/lsyncd.log",
    statusFile = "/var/log/lsyncd-status.log",
    statusInterval = 20
}

sync {
    default.rsync,
    source = "/source/directory",
    target = "user@remote_host:/destination/directory",
    rsync = {
        archive = true,
        compress = true,
        verbose = true
    }
}

启动服务:

sudo systemctl start lsyncd
sudo systemctl enable lsyncd

3. Syncthing - 跨平台GUI同步工具

安装:

# Debian/Ubuntu
sudo apt install syncthing

# CentOS/RHEL
sudo yum install syncthing

启动并设置开机自启:

systemctl --user start syncthing
systemctl --user enable syncthing

访问Web界面: http://localhost:8384

4. Unison - 双向同步工具

安装:

sudo apt install unison  # Debian/Ubuntu
sudo yum install unison # CentOS/RHEL

基本用法:

unison /local/directory ssh://user@remote//remote/directory

5. 使用云存储同步

Rclone

# 配置
rclone config

# 同步到Google Drive
rclone sync /local/path remote:path

Nextcloud客户端

sudo apt install nextcloud-client  # Debian/Ubuntu

安全建议

  1. 使用SSH密钥认证而非密码
  2. 限制同步目录的最小必要权限
  3. 考虑使用--bwlimit限制带宽(rsync)
  4. 对于敏感数据,考虑加密同步

选择建议

  • 简单定时同步: rsync + cron
  • 实时同步: lsyncd
  • 图形界面/跨平台: Syncthing
  • 双向同步: Unison
  • 云存储集成: Rclone

需要更具体的解决方案或有任何疑问,请提供您的具体使用场景和需求。