16  实现inotify配合rysnc实时备份

(一):服务端的守护进程模式和客户端的rsync配置

1.配置服务端rysnc

    vi /etc/rsyncd.conf里的内容

uid = rsync      
gid = rsync      
use chroot = no      
max connections = 200      
timeout = 100      
pid file = /var/run/rsyncd.pid      
lock file = /var/run/rsync.lock      
log file  = /var/log/rsyncd.log      
[backup]      
path = /backup/      
ignore errors      
read only = false      
list =  false      
hosts allow = 199.101.117.0/24      
hosts deny = 0.0.0.0/32      
auth users = rsync_backup      
secrets file = /etc/rsync.password


##如果在windows下编辑或者复制的编码到linux下就最好用这个命令处理下Dos2unix /etc/rsyncd.conf

[root@test*** backup]#mkdir /backup

[root@test*** backup]#useradd rsync -s /bin/nologin –M                            

## 新建个账户(和配置文件的uid-gid对应,此账户属性不能登录并且没目录)

[root@test*** backup]#chown -R rsync.rsync /oldboy                                

[root@test*** backup]#echo “rsync_backup:oldboy”> /etc/rsync.password  

##rsync_backup是虚拟账户,到时候客户端连接就用这个账户和密码oldboy。

[root@test*** backup]#chmod 600 /etc/rsyncd.password                                   ###设置成别人都不能看到,因为里面有密码

[root@test*** backup]#rsync --daemon  

#启动进程





2.到客户端配置:只要这两步即可

[root@twstaiton2 ~]#echo “oldboy”>/etc/rsync.password                        

#这个路径和服务端路径没任何关系,为了规范而已,密码必须和服务那相同

[root@twstaiton2 ~]#chmod 600 /etc/rsync.password






二):客户端的inotify部署


[root@twstaiton2 ~]#wget  http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz

[root@twstaiton2 ~]# ll /proc/sys/fs/inotify/

total 0

-rw-r--r-- 1 root root 0 Jan 21 00:34 max_queued_events

-rw-r--r-- 1 root root 0 Jan 21 00:34 max_user_instances

-rw-r--r-- 1 root root 0 Jan 21 00:34 max_user_watches

####检查命令;能看到这三个说明支持inotify,执行下面命令(可批量复制执行)

[root@twstaiton2 ~]#tar zxf inotify-tools-3.14.tar.gz

[root@twstaiton2 ~]#cd inotify-tools-3.14

[root@twstaiton2 ~]#./configure --prefix=/usr/local/inotify-tools-3.14

[root@twstaiton2 ~]#make && make install

[root@twstaiton2 ~]#ln -s /usr/local/inotify-tools-3.14 /usr/local/inotify

##vps需装make gcc gcc++,/usr/local/inotify/bin/inotifywait --help里有众多参数,但只需记得createdelete参数,用于侦听事件来触发inotify


编写一个脚本inotify如下:

[root@twstaiton2 ~]#vi realtime.sh

#!/bin/bash

host01=199.101.117.34

src=/backup

dst=backup

user=rsync_backup

rsync_passfile=/etc/rsync.password

inotify_home=/usr/local/inotify


if [ ! -e "$src" ] \

|| [ ! -e "${rsync_passfile}" ] \

|| [ ! -e "${inotify_home}/bin/inotifywait" ] \

|| [ ! -e "/usr/bin/rsync" ];

then

echo "Check File and Folder"

exit 0

fi


${inotify_home}/bin/inotifywait -mrq --timefmt '%d%m%y %H:%M' --format '%T %w%f' -e close_write,delete,create,attrib $src \

| while read file

   do

    cd $src && rsync -aruz -R --delete ./ --timeout=100 $user@$host01::$dst --password-file=${rsync_passfile} >/dev/null 2>&1

    done

exit 0

##以上是脚本内容

[root@twstaiton2 ~]#nohup ./realtime.sh &   #启动后台监听脚本

在/backup目录下测试touch {1..100},在服务端的/backup马上会同步这100个文件,成功!

如果不成功需要手动一个个命令检查,有关rsync的服务端配置,详见 Rsync 的简单应用与配置这篇文章