#主备机器都安装rsync和inotify-tools
sudo apt-get -y install rsync inotify-tools
#使用nginx配置文件测试:
/tmp# cd /tmp && cp -rf /usr/local/nginx/conf/ nginx_conf
#初始同步
rsync -avz --delete /tmp/nginx_conf root@10.80.7.14:/tmp
#!/bin/bash
# 定义源目录和目标目录的映射关系
declare -A paths=(
["/usr/local/nginx/conf"]="root@10.80.7.14:/usr/local/nginx/conf"
["/data/wwwroot"]="root@10.80.7.14:/data/wwwroot"
["/data/service"]="root@10.80.7.14:/data/service"
)
log_file="/data/logs/rsync/sync.log" # 日志文件路径
# 同步函数,将指定的源目录同步到目标目录
sync_files() {
local source_dir="$1"
local destination_dir="$2"
echo "$(date '+%Y-%m-%d %H:%M:%S') - Syncing files in $source_dir..." >> "$log_file"
rsync -avz --delete "$source_dir/" "$destination_dir" >> "$log_file" 2>&1
echo "$(date '+%Y-%m-%d %H:%M:%S') - Sync complete for $source_dir." >> "$log_file"
}
# 并发处理函数,用于监控和同步指定的目录
process_dir() {
local source_dir="$1"
# 用于获取关联数组 paths 中指定键 $source_dir 对应的值(value)
local destination_dir="${paths[$source_dir]}"
# 监控并同步指定的目录
while inotifywait -r -e modify,create,delete,move "$source_dir"; do
sync_files "$source_dir" "$destination_dir"
done
}
# 同时监控和同步多个目录
for source_dir in "${!paths[@]}"; do
process_dir "$source_dir" & # 在后台运行处理函数
done
wait # 等待所有后台进程完成
[Unit]
Description=File monitoring and synchronization service
[Service]
ExecStart=/opt/script/monitor.sh
[Install]
WantedBy=multi-user.target
#启用和启动服务
sudo systemctl enable monitor
sudo systemctl start monitor
#检查服务的状态
sudo systemctl status monitor
#停止服务
sudo systemctl stop monitor