Ubuntu定时任务同步的常见方法
rsync是Ubuntu下高效的文件同步工具,结合SSH免密登录可实现安全的定时同步。
sudo apt install rsync。ssh-keygen -t rsa,将公钥复制到目标服务器ssh-copy-id username@destination_ip(替换为目标服务器用户名和IP)。sync_script.sh,内容为rsync -avz /source/folder/ username@destination_ip:/target/folder/(-a保留文件属性,-v显示详情,-z压缩传输),赋予执行权限chmod +x sync_script.sh。crontab -e,添加定时规则(如每小时同步一次:0 * * * * /path/to/sync_script.sh),保存后自动生效。systemd定时器更灵活,支持依赖管理和日志记录,适合需要精准调度的场景。
/etc/systemd/system/sync.service,内容为:[Unit]
Description=File Sync Service
[Service]
ExecStart=/usr/bin/rsync -avz /source/folder/ /target/folder/
/etc/systemd/system/sync.timer,内容为:[Unit]
Description=Run sync every hour
[Timer]
OnCalendar=hourly
Persistent=true
[Install]
WantedBy=timers.target
sudo systemctl enable sync.timer和sudo systemctl start sync.timer,定时器会自动触发服务执行同步。Unison是双向同步工具,适合需要保持两端目录完全一致的场景(如开发环境与服务器代码同步)。
sudo apt install unison(两端服务器均需安装,版本尽量一致)。unison_sync.sh,内容为unison /source/folder ssh://username@destination_ip//target/folder/ -auto -batch(-auto自动确认非冲突操作,-batch非交互模式),赋予执行权限chmod +x unison_sync.sh。crontab -e添加定时规则(如每天凌晨2点同步:0 2 * * * /path/to/unison_sync.sh)。Syncthing是开源的点对点同步工具,无需中心服务器,支持实时或定时同步多设备。
sudo apt install syncthing,启动服务sudo systemctl enable --now syncthing@your_username。http://localhost:8384,添加本地目录(如/source/folder),并邀请目标设备(输入其Syncthing ID)加入同步。crontab -e添加脚本控制Syncthing的同步操作(如每小时执行一次syncthingctl sync your_device_id)。