配置rsync+inotify实时同步

来源:互联网 发布:it企业招人难 编辑:程序博客网 时间:2024/05/18 02:00

Linux内核从2.6.13版本开始提供了inotify通知接口,用来监控文件系统的各种变化情况,如文件存取、删除、移动等。利用这一机制,可以非常方便地实现文件异动告警、增量备份,并针对目录或文件的变化及时作出响应。
使用rsync工具与inotify机制相结合,可以实现触发式备份(实时同步)
  • 部署环境 (CentOS 6.6):

把 192.168.198.131 上的/var/www/html目录时实同步到
-> 192.168.198.132 上的/wwwroot目录中
在 131 上执行下面的相关操作,实现实时同步:

  看看是否有 /proc/sys/fs/inotify/目录,以确定内核是否支持inotify

ll /proc/sys/fs/inotify/total 0-rw-r--r-- 1 root root 0 Feb  4 10:06 max_queued_events-rw-r--r-- 1 root root 0 Feb  4 10:06 max_user_instances-rw-r--r-- 1 root root 0 Feb  4 10:06 max_user_watches


  默认的inotify机制提供了三个调控参数:max_queued_events、max_user_instances、max_user_watches。分别表示监控事件队列、最多监控实例数、每个实例最多监控文件数

tail /proc/sys/fs/inotify/*==> /proc/sys/fs/inotify/max_queued_events <==16384==> /proc/sys/fs/inotify/max_user_instances <==128==> /proc/sys/fs/inotify/max_user_watches <==8192


  当要监控的目录、文件数量较多或者变化较频繁时,建议加大这三个参数的值。
例如可直接修改/etc/sysctl.conf配置文件,将管理队列设为32768,实例数设为1024,监控数设为1048576(建议大于监控目标的总文件数)。

vim /etc/sysctl.conf    #添加如下内容fs.inotify.max_queued_events = 32768fs.inotify.max_user_instances = 1024fs.inotify.max_user_watches = 1048576sysctl -p               #使修改后文件生效


  • 安装inotify-tools工具

  使用inotify机制还需要安装inotify-tools,以便提供inotifywait、inotifywatch辅助工具程序,用来监控、汇总改动情况。

yum -y install epel-releaseyum install inotify-tools --enablerepo=epel


inotifywait命令

inotifywait -mrq -e create,delete,move,modify,attrib /var/www/html/-e 指定监控事件(create,move,delete,modify,attrib"创建,移动,删除,写入,属性事件"-m 表示持续监控-r 表示递归整个目录-q 表示简化输出信息


rsync选项的含义:

-a 存档模式-h 保存硬连接-z 压缩文件数据在传输-t 维护修改时间--delete 删除于多余文件
  • 配置好基于密钥身份验证的SSH服务

132主机:

useradd adminput ; passwd adminputchown adminput.adminput /wwwroot


131主机:

ssh-keygen -t rsassh-copy-id adminput@192.168.198.132


  • 编写触发式同步脚本

  为了简单起见,只要检测到变动时执行rsync上行同步操作即可。需要注意的是,当更新较频繁时,应避免并发执行rsync备份(当rsync进程已经存在则忽略本次同步,或根据rsync进程数量来决定是否同步)

vim /opt/inotify.sh#!/bin/bashINOTIFY_CMD="inotifywait -mrq -e create,delete,move,modify,attrib /var/www/html/"RSYNC_CMD="rsync -azH --delete /var/www/html/ adminput@192.168.198.131:/wwwroot"$INOTIFY_CMD | while read DIRECTORY EVENT FILEdo    if [ $(pgrep rsync | wc -l) -le 0 ] ; then        $RSYNC_CMD#       echo "${FILE} was rsynced" >>/opt/inotify_rsync.log    fidone


chmod +x /opt/inotify.shecho "bash /opt/inotify.sh" >> .bash_profile

  注:脚本内容检测rsync进程数,脚本名不要包含rsync,如要包含,调整下检测的rsync进程数


转载请务必保留此出处:http://blog.csdn.net/fgf00/article/details/50732743

原创粉丝点击