實現 Linux 伺服器資料自動同步至 Windows 備份主機,採用 Rsync Daemon 模式 (效能優於 SSH 模式) 搭配 Windows cwRsync 客戶端,配合 Windows 工作排程器實現每日定時增量備份。本文含防火牆、認證、模組配置、雙向驗證全流程。
| 角色 | 作業系統 | IP | 資料目錄 |
|---|---|---|---|
| Rsync 服務端 | Ubuntu Server 11.10 | 192.168.21.168 | /home/mysql_data |
| cwRsync 客戶端 | Windows Server 2003 | 192.168.21.130 | D:\mysql_data |
目標: 客戶端每日 03:00 自動從服務端拉取 /home/mysql_data 至 D:\mysql_data。
Ubuntu 預設無防火牆,生產環境建議啟用 iptables:
# 檢查/安裝 iptables
whereis iptables
apt-get install iptables
# 編輯規則檔 /etc/iptables.default.rules
*filter
-A INPUT -i lo -j ACCEPT
-A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
-A OUTPUT -j ACCEPT
-A INPUT -p tcp --dport 80 -j ACCEPT
-A INPUT -p tcp --dport 3306 -j ACCEPT
-A INPUT -p tcp --dport 873 -j ACCEPT # Rsync 埠
-A INPUT -p tcp -m state --state NEW --dport 22 -j ACCEPT
-A INPUT -p icmp --icmp-type 8 -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "iptables denied: "
-A INPUT -j REJECT
-A FORWARD -j REJECT
COMMIT
# 套用並設定開機載入
iptables-restore < /etc/iptables.default.rules
echo '#!/bin/bash
/sbin/iptables-restore < /etc/iptables.default.rules' > /etc/network/if-pre-up.d/iptables
chmod +x /etc/network/if-pre-up.d/iptables
apt-get install rsync
# 編輯 /etc/default/rsync
RSYNC_ENABLE=true
/etc/rsyncd.conf 核心配置
log file = /var/log/rsyncd.log
[MySQL_Backup]
path = /home/mysql_data
comment = MySQL_Backup
uid = root
gid = root
port = 873
read only = no
write only = no
auth users = mysqlbakuser
secrets file = /etc/rsync.pass
hosts allow = 192.168.21.130
hosts deny = 192.168.21.254
list = yes
read only = no 允許雙向 (客戶端可上傳/下載);單向備份建議 read only = yes。auth users 對應密碼檔帳號;hosts allow 限制來源 IP。
echo "mysqlbakuser:123456" > /etc/rsync.pass
chmod 600 /etc/rsyncd.conf /etc/rsync.pass
/etc/init.d/rsync start
# 或 service rsync start / systemctl start rsync (新版)
netstat -ntlp | grep 873 # 驗證監聽
cwRsync_4.0.3_Installer.zip 解壓安裝,預設路徑 C:\Program Files\cwRsync。




cmd
cd C:\Program Files\cwRsync\bin
telnet 192.168.21.168 873
出現連線成功畫面 (空白游標閃爍) 即代表埠口通達。


rsync -vzrtopg --progress --delete mysqlbakuser@192.168.21.168::MySQL_Backup /cygdrive/d/mysql_data
/cygdrive/d/mysql_data = Windows D:\mysql_data (Cygwin 路徑格式)。MySQL_Backup = 服務端 rsyncd.conf 中 [MySQL_Backup] 模組名。123456 (對應 /etc/rsync.pass)。

對比 D:\mysql_data 與遠端 /home/mysql_data 檔案數量、大小、修改時間。

sync_mysql.bat:
@echo off
cd /d "C:\Program Files\cwRsync\bin"
rsync -vzrtopg --progress --delete --password-file=rsync.pass mysqlbakuser@192.168.21.168::MySQL_Backup /cygdrive/d/mysql_data >> D:\logs\rsync_sync_%date%.log 2>&1
rsync.pass 檔 (僅含密碼 123456),chmod 600 對等保護。--password-file 避免互動式輸入密碼,適合排程。sync_mysql.bat → 完成。
-vzrtopg --progress --delete
-v 詳細輸出
-z 壓縮傳輸
-r 遞迴
-t 保留修改時間
-o 保留擁有者 (需 root)
-p 保留權限
-g 保留群組
--progress 顯示進度
--delete 刪除目的端多餘檔案 (鏡像模式)
生產環境加固建議: 1) 服務端
read only = yes僅允許下載;2) 使用 SSH 通道替代明文 Daemon (stunnel/SSH 隧道);3) 定期輪換rsync.pass密碼;4) 監控日誌檔大小與同步耗時,異常告警。