034Ubuntu下rsync和inotify实现多路径文件实时同步

一、安装

#安装rsync和inotify-tools
sudo apt-get install rsync inotify-tools

#使用nginx配置文件测试:
/tmp# cp -rf  /usr/local/nginx/conf/  nginx_conf

#初始同步
rsync -avz --delete /tmp/nginx_conf root@192.168.0.82:/tmp
vim /opt/script/monitor.sh
#!/bin/bash

# 定义源目录和目标目录的映射关系
declare -A paths=(
  ["/usr/local/nginx/conf"]="root@192.168.0.82:/usr/local/nginx/conf"
  ["/data/wwwroot"]="root@192.168.0.82:/data/wwwroot"
)

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  # 等待所有后台进程完成

三、使用systemd使脚本一直运行

#在源机器上创建一个systemd服务单元文件以管理monitor.sh脚本的运行。在终端中使用以下命令创建一个新的服务单元文件(例如monitor.service):
vim /etc/systemd/system/monitor.service

#在编辑器中输入以下内容:
[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

 

 

posted @ 2023-05-17 22:38  arun_yh  阅读(233)  评论(0编辑  收藏  举报