rsync+inotify实现服务器间文件的实时同步

    rsync虽然可以实现触发式的文件同步,但是通过crontab守护进程方式进行触发,同步的数据和实际数据会有差异,而inotify可以监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,这样刚好解决了我的需求,同步数据实时性的问题,下面便看我娓娓道来。

一) lists

Ip

Status

Cp  PATH

App

192.168.1.1

Server

/data

Rsync-server

192.168.1.2

Client

/OM/logs/data

Rsync-client+inotify

二)需求

    server端服务器(192.168.1.1)像client端服务器(192.168.1.2)同步数据,并让inotify监听操作。

    如果client端的/OM/logs/data下面有创建、删除等文件操作,server端也会相应的实时同步数据文件。

 

三)实战

Server:1.创建rsync主配置文件rsyncd.conf

 [email protected] :/etc# vi /etc/rsyncd.conf
log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
max connections = 100
use chroot = no
uid = root
gid = root
ignore errors
list = no
[example]
path = /OM/logs/data
read only = no                    #no客户端可上传文件,yes只读
write only = no                    #no客户端可下载文件,yes不能下载
auth users = aaron              # 认证的用户名,如果没有这行,则表明是匿名
secrets file = /etc/rsyncd.passwd        # 指定认证口令文件位置
hosts allow = 192.168.1.2
hosts deny = *

          2.创建密码验证文件,rsyncd.passwd

[email protected]:/etc# vi rsyncd.passwd   
aaron:bu/I*)NEj

          3.修改密码文件权限 

chmod 600 rsync.passwd

          4.启动Rsync

 /usr/bin/rsync --daemon

Client:1,创建密码验证文件rsyncd.passwd,这里只需要输入密码就可以了。

# vi rsyncd.passwd   
bu/I*)NEj

         2.安装inotify

  1. [[email protected] ]# cd /app
    [[email protected]  app]# wget http://cloud.github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz  
    [[email protected]  app]# tar zxvf inotify-tools-3.14.tar.gz  
    [[email protected]  app]# cd inotify-tools-3.14  
    [[email protected] inotify-tools-3.14]# ./configure --prefix=/usr/local/inotify  
    [[email protected] inotify-tools-3.14]# make  
    [[email protected] inotify-tools-3.14]# make install

        3.创建同步脚本

#!/bin/bash
host=192.168.1.1
src=/data
des=example
user=aaron
/usr/local/inotify/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f%e' -e modify,delete,create,attrib $src | while read files
do
/usr/bin/rsync -vzrtopg --delete  --progress --password-file=/etc/rsyncd.passwd $src $user@$host::$des
echo "${files} was rsynced" >>/var/log/rsync.log 2>&1
done

        4.修改脚本权限并运行

chmod 764 rsync.sh
nohup rsync.sh &

        5.讲脚本加入开机启动项

echo "/usr/local/inotify/rsync.sh" >> /etc/rc.local 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章