Ubuntu下用Rsync+iNotify完成文件单向同步


2023-06-06 08:10:37

需求场景:两台ubuntu服务器,从源服务器(代码:src)同步两个目录中内容,到目的服务(代码:dest)的同一目录下。

src 开启rsync

  • sudo vi /etc/default/rsync
RSYNC_ENABLE=true
            

src生成ssh id, 并copy到dest,以打通ssh

src 安装inotify-tools

  • apt-get install inotify-tools

src 监控目录变化+同步脚本1

  • sudo vi inotifywait-rsync-dir1.sh
inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,moved_to /home/src-user/src-dir1 | while read file
            do
            rsync -az --progress /home/src-user/src-dir1 dest-user@dest-server:/home/dest-user/dest-dir
            echo "${file} was synchronized" >> /home/src-user/rsync_log/rsync.log 2>&1
            done
            
  • mkdir /home/src-user/rsync_log

src 监控目录变化+同步脚本2

  • sudo vi inotifywait-rsync-dir2.sh
inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e modify,delete,create,moved_to /home/src-user/src-dir2 | while read file
            do
            rsync -az --progress /home/src-user/src-dir2/ dest-user@dist-server:/home/dest-user/dest-dir/
            echo "${file} was synchronized" >> /home/src-user/rsync_log/rsync2.log 2>&1
            done
            

src 加入开机启动

  • sudo vi /etc/profile
/bin/bash /home/src-user/inotifywait-rsync-dir1.sh&
            /bin/bash /home/src-user/inotifywait-rsync-dir2.sh&
            

dest 接收端开启rsync

  • sudo vi /etc/default/rsync
RSYNC_ENABLE=true