039rsync和inotify实时文件同步

安装

  • 注意把ip换一下
#主备机器都安装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
mkdir -p /data/logs/rsync/ && touch /data/logs/rsync/sync.log
mkdir /opt/script/ && vim /opt/script/monitor.sh && chmod a+x *.sh
#!/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  # 等待所有后台进程完成

使用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 @ 2024-04-09 09:40  arun_yh  阅读(34)  评论(0)    收藏  举报