Rsync 是 Linux 系統級增量同步工具,支援守護進程模式(Server/Client)實現高效、認證、帶寬控制的跨服務器文件同步。本文詳細記錄雙向/單向同步架構、xinetd 托管配置、認證授權、排除規則與 Crontab 定時策略。
rsync --daemon,提供只讀/讀寫模組,數據權威源。rsync -avz 從 A 拉取數據。yum install -y rsync xinetd
# 編輯 xinetd 服務定義
cat > /etc/xinetd.d/rsync <<'EOF'
service rsync
{
disable = no
flags = IPv4
socket_type = stream
wait = no
user = root
server = /usr/bin/rsync
server_args = --daemon
log_on_failure += USERID
}
EOF
systemctl restart xinetd
systemctl enable xinetd
# 或 service xinetd restart; chkconfig xinetd on
uid = root
gid = root
use chroot = no
max connections = 10
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsyncd.lock
log file = /var/log/rsyncd.log
transfer logging = yes
timeout = 300
port = 873
[www] # 模組名,客戶端用 ::www 訪問
path = /home/www # 同步源目錄
comment = Web root sync
read only = yes # 只讀,源端通常不接受推送
list = yes # 允許客戶端列出模組
auth users = rsync_user # 虛擬用戶,不需系統賬號
secrets file = /etc/rsyncd.passwd
hosts allow = 10.0.0.0/8, 192.168.0.0/16 # 允許網段
hosts deny = *
exclude = .git/ node_modules/ *.log tmp/ cache/ # 排除規則
# 進階: 讀寫模組需 write only = no, 配合 incoming/outgoing chroot
# 格式: 用戶名:密碼 (明文,僅 rsync 守護進程使用)
echo "rsync_user:StrongRandomPassword123!" > /etc/rsyncd.passwd
chmod 600 /etc/rsyncd.passwd
firewall-cmd --permanent --add-port=873/tcp
firewall-cmd --reload
# 或 iptables -I INPUT -p tcp --dport 873 -j ACCEPT
echo "StrongRandomPassword123!" > /etc/rsyncd.passwd
chmod 600 /etc/rsyncd.passwd
rsync -avz --delete --progress \
--password-file=/etc/rsyncd.passwd \
rsync_user@192.168.1.100::www \
/home/www/
| 參數 | 含義 |
|---|---|
-a | 歸檔模式 = -rlptgoD (遞歸、保留鏈接、權限、時間、組、擁有者、設備) |
-v | 詳細輸出 |
-z | 傳輸壓縮 (LAN 可省略,WAN 建議開啟) |
--delete | 刪除目標端源端不存在的文件 (鏡像同步,慎用) |
--progress | 顯示單文件進度 |
--password-file | 指定密碼文件,避免交互輸入 |
--bwlimit=10240 | 限制帶寬 10MB/s,避免佔滿業務帶寬 |
--exclude-from=/etc/rsync_exclude.txt | 外部排除文件列表 |
#!/bin/bash
set -euo pipefail
LOG="/var/log/rsync_www.log"
SRC="rsync_user@192.168.1.100::www"
DEST="/home/www"
PASS="/etc/rsyncd.passwd"
BWLIMIT="20480" # 20MB/s
echo "$(date '+%F %T') ==== Sync START ====" >> "$LOG"
rsync -avz --delete --progress \
--bwlimit="$BWLIMIT" \
--password-file="$PASS" \
"$SRC" "$DEST" >> "$LOG" 2>&1
RET=$?
echo "$(date '+%F %T') ==== Sync END (exit $RET) ====" >> "$LOG"
exit $RET
chmod +x /root/sync_www.sh
# 編輯 root crontab
crontab -e
# 每 15 分鐘同步一次 (高頻業務)
*/15 * * * * /root/sync_www.sh
# 或每小時整點 (常規業務)
0 * * * * /root/sync_www.sh
# 每天凌晨 2:30 低峰全量校驗
30 2 * * * /root/sync_www.sh --checksum
# 測試連通性
rsync --list-only rsync_user@192.168.1.100::www --password-file=/etc/rsyncd.passwd
# 手動執行腳本觀察日誌
/root/sync_www.sh
tail -f /var/log/rsync_www.log
# 檢查守護進程狀態
netstat -ntulp | grep 873
ps aux | grep rsync
Rsync 本質單向,雙向同步需雙向運行或使用 Unison(雙向同步、圖形/文本界面、衝突檢測、指紋緩存)。生產環境建議:
rclone / aws s3 sync / ossutil。