架構概覽
- Server 端:運行 rsync daemon (port 873),提供模組供客戶端拉取/推送。
- Client 端:執行
rsync 指令同步資料,可搭配 cron 定時/腳本推送。
一、Server 端配置 (CentOS/RHEL)
1. 安裝 xinetd 與 rsync
yum -y install xinetd rsync
2. 啟用 xinetd 管理的 rsync 服務
vi /etc/xinetd.d/rsync
# 將 disable = yes 改為 disable = no
service rsync
{
disable = no
socket_type = stream
wait = no
user = root
server = /usr/bin/rsync
server_args = --daemon
log_on_failure += USERID
}
service xinetd restart
# 或 systemctl restart xinetd (CentOS 7+)
3. 防火牆開放 873 埠
# iptables (CentOS 6)
iptables -A INPUT -s 192.168.0.0/24 -p tcp --dport 873 -j ACCEPT
iptables -A INPUT -p tcp --dport 873 -j DROP
service iptables save
# firewalld (CentOS 7+)
firewall-cmd --permanent --add-port=873/tcp
firewall-cmd --reload
4. 建立 rsyncd.conf 主配置
vi /etc/rsyncd.conf
# Global Settings
uid = root
gid = root
use chroot = no
max connections = 20
secrets file = /etc/rsyncd.secrets
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
comment = Backup Server
[backup]
path = /data/www/repos
auth users = rsync_user
read only = no
hosts allow = 192.168.3.128
hosts deny = *
list = true
# exclude = cache/ temp/
5. 建立認證檔
vi /etc/rsyncd.secrets
rsync_user:StrongPassword123
chown root:root /etc/rsyncd.secrets
chmod 600 /etc/rsyncd.secrets # 必須 600,否則啟動失敗
二、Client 端同步操作
1. 安裝 rsync
yum -y install rsync
2. 手動同步測試
# 密碼檔僅需密碼 (無用戶名)
echo "StrongPassword123" > /etc/rsyncd.pass
chmod 600 /etc/rsyncd.pass
# 拉取模式 (Server → Client)
rsync -avz --progress --delete --password-file=/etc/rsyncd.pass rsync_user@192.168.3.191::backup /www/
# 推送模式 (Client → Server)
rsync -avz --progress --delete --password-file=/etc/rsyncd.pass /www/ rsync_user@192.168.3.191::backup
3. 參數詳解
| 參數 | 含義 |
-a | 封存模式 = -rlptgoD (遞歸、保留連結/權限/時間/擁有者/裝置/特殊檔) |
-v | 顯示詳細傳輸過程 |
-z | 傳輸時壓縮 |
-u | update:略過目標端較新檔案 |
--progress | 顯示進度條與速率 |
--delete | 刪除目標端來源不存在的檔案 (鏡像同步) |
-e ssh | 透過 SSH 加密通道 (需 SSH 金鑰免密) |
4. 定時自動同步 (crontab)
crontab -e
# 每 3 分鐘同步一次
*/3 * * * * rsync -avz --delete --password-file=/etc/rsyncd.pass rsync_user@192.168.3.191::backup /www/ >/var/log/rsync_sync.log 2>&1
三、常用指令速查
1. 列舉遠端模組/目錄
rsync rsync_user@192.168.3.191:: # 列出模組
rsync rsync_user@192.168.3.191::backup # 列出 backup 模組內容
2. 本地目錄同步
rsync -av --progress /src/ /dst/ # 同步 src 內容至 dst
rsync -av --progress /src /dst/ # 同步 src 目錄本身至 dst/src
3. SSH 模式同步 (無需 rsync daemon)
rsync -avz -e ssh /src/ user@remote:/dst/
rsync -avz -e ssh user@remote:/src/ /dst/
四、故障排查
@ERROR: auth failed → 檢查密碼檔權限 600、用戶名拼寫、secrets file 路徑。
@ERROR: chroot failed → use chroot = no 或確保路徑權限允許 chroot。
Connection refused → 確認 xinetd/rsync daemon 運行、防火牆、SELinux (setsebool -P rsync_full_access 1)。
- 傳輸緩慢 → 加
-z 壓縮、檢查磁碟 I/O、網路頻寬、考慮 --bwlimit 限速。