欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

rsync+inotify

最编程 2024-04-09 06:58:33
...

一、概念

使用inotify通知接口,可以用来监控文件系统的各种变化情况,如文件存取、删除、移动、修改等。利用这一机制,可以非常方便地实现文件异动告警、增量备份,并针对目录或文件的变化及时作出响应。将inotify机制与rsync工具相结合,可以实现触发式备份(实时同步),即只要原始位置的文档发生变化,则立即启动增量备份操作;否则处于静默等待状态。这样,就避免了按固定周期备份时存在的延迟性、周期过密等问题。因为 inotify 通知机制由 Linux 内核提供,因此主要做本机监控,在触发式备份中应用时更适合上行同步。

二、 配置

2.1 修改rsync源服务器配置文件

vim /etc/rsyncd.conf
read only = no											#关闭只读,上行同步需要可以写
kill $(cat /var/run/rsyncd.pid)
rm -rf /var/run/rsyncd.pid
rsync --daemon	
netstat -anpt | grep rsync
chmod 777 /var/www/html/

2.2 调整 inotify 内核参数

在Linux内核中,默认的inotify机制提供了三个调控参数:
max_queue_events(监控事件队列,默认值为16384)、
max_user_instances(最多监控实例数,默认值为128)、
max_user_watches(每个实例最多监控文件数,默认值为8192)。当要监控的目录、文件数量较多或者变化较频繁时,建议加大这三个参数的值。

vim /etc/sysctl.conf
fs.inotify.max_queued_events = 16384
fs.inotify.max_user_instances = 1024
fs.inotify.max_user_watches = 1048576
sysctl -p

2.3 安装 inotify-tools

[root@localhost ~]# cd /opt
 
[root@localhost opt]# rz -E
 
#传入 inotify-tools 安装包
 
rz waiting to receive.
 
tar zxvf inotify-tools-3.14.tar.gz -C /opt
 
 cd inotify-tools-3.14/
 
 ./configure
 
 make -j 2 && make install

2.3.1 新终端操作

[root@localhost ~]# cd /var/www/html/test
 
[root@localhost test]# touch test.php
 
[root@localhost test]# mv test.php test.txt
 
[root@localhost test]# echo 'test' > test.txt
 
[root@localhost test]# rm -rf test.txt

2.3.2 原终端操作

inotifywait -mrq -e modify,create,move,delete /var/www/html/test

(1)选项“-e”:用来指定要监控哪些事件

(2)选项“-m”:表示持续监控

(3)选项“-r”:表示递归整个目录

(4)选项“-q”:简化输出信息

2.3.3 在新终端的/var/www/html/test的目录下新建文件夹

mkdir test1

2.3.4 在原终端上显示该内容

inotifywait -mrq -e modify,create,move,delete /var/www/html/test

2.4 在另外一个终端编写触发式同步脚本

#!/bin/bash
 
INOTIFY_CMD="inotifywait -mrq -e modify,create,attrib,move,delete /var/www/html/test"
 
RSYNC_CMD="rsync -azH --delete --password-file=/etc/server.pass /var/www/html/test backuper@192.168.133.20::rsync/"
 
$INOTIFY_CMD | while read DIRECTORY EVENT FILE
##while判断是否接收到监控记录
 
do
 
    if [ $(pgrep rsync | wc -l) -le 0 ] ; then
 
        $RSYNC_CMD
 
    fi
 
done
chmod +x /opt/inotify.sh
chmod 777 /var/www/html/
chmod +x /etc/rc.d/rc.local
echo '/opt/inotify.sh' >> /etc/rc.d/rc.local				#加入开机自动执行

注意:上述脚本用来检测本机 /var/www/html/test 目录的变动情况,一旦有更新触发 rsync 同步操作,上传备份至服务器 192.168.133.20 的 rsync 共享目录下。

2.4.1 在本机运行 /opt/inotify_rsync.sh 脚本程序

./inotify.sh &        //后台运行该脚本

2.4.2 切换到本机的 /var/www/html 目录,执行增加、删除、修改文件等操作

[root@localhost test]# rm -rf *
 
[root@localhost test]# touch test.html
 
[root@localhost test]# echo 'this is inotify_rsync test!' > test.html

2.4.3 查看远端服务器中的 rsync 目录下的变化情况

未完待续

推荐阅读