前言

  • 系统:centos 7
  • inotify-tools版本:3.14(3.22版本测试有问题,所以找的比较旧的一版)
  • 主机IP:
    • 192.168.137.7(服务端,接收同步文件)
    • 192.168.137.8(客户端,发送同步文件)
  • github下载inotify-tools的源码压缩包
  • 需求:客户端的/home/testpath目录和服务端的/home/testpath同步。客户端目录有变动时,同步复制到服务端

    编译安装inotify

  1. 安装依赖

    1. yum install -y autoconf automake libtool make gcc gcc-c++ make
  2. 客户端解压,编译,安装 ```shell tar xf inotify-tools-3.14.tar.gz cd inotify-tools-3.14 ./autogen.sh ./configure —prefix=/home/apps/inotify-tools make make install

inotifywait: 仅执行阻塞,等待inotify事件

inotifywatch: 收集关于被监视文件系统的统计数据

  1. 3. 两台主机都安装rsync
  2. ```shell
  3. yum install -y rsync
  1. 服务端编辑rsync配置文件 /etc/rsyncd.conf ``` uid = root gid = root usechroot = no max connections = 20 timeout = 600 pid file = /var/run/rsyncd.pid lock file = /var/run/rsync.lock log file = /var/log/rsyncd.log

[testpath] path = /home/testpath ignore errors read only = false writeonly = false list = false hosts allow = 192.168.137.8 auth users = backuser secrets file = /etc/rsync.pass

  1. 5. 编辑用户文件 /etc/rsync.pass,编辑完成后修改权限:chmod 600 /etc/rsync.pass
  2. ```shell
  3. backuser:123
  1. 客户端编辑 /etc/rsync.pass,编辑完成后修改权限:chmod 600 /etc/rsync.pass

    1. 123
  2. 客户端测试rsync传输

    1. rsync -a --progress /home/tmp/* backuser@192.168.137.7::testpath --password-file=/etc/rsync.pass
  3. 编辑inotify.sh脚本 ```shell

    !/bin/bash

set -u

src=/home/testpath

/home/apps/inotify-tools/bin/inotifywait -mrq —timefmt ‘%d/%m/%y %H:%M’ —format ‘%T %w%f’ -emodify,delete,create,attrib $src | while read file do rsync -zrtopg —progress $src/* backuser@192.168.137.7::testpath —password-file=/etc/rsync.pass echo “$(date) rsync event occur” >> /home/scripts/inotify.log 2>&1 done

  1. 9. 赋予可执行权限并运行。
  2. ```shell
  3. chmod +x inotify.sh
  4. ./inotify.sh &
  1. 测试

    补充

  • inotifywait选项

    1. -h: 帮助信息
    2. -m: 接收到事件时不退出。默认接收到一个事件后即退出
    3. -r: 监视一个目录下的所有子目录
    4. -q: 安静模式
    5. -e: 指定监听的事件
    6. -timefmt: 指定时间格式,用于format的%T
    7. --format: 指定输出格式
    8. %T: 时间格式
    9. %f: 发生事件的文件
    10. %w: 发生事件的目录
    11. %e: 发生的事件
  • inotifywait可监听事件,配合-e选项

    1. access: 文件读取
    2. modify: 文件修改
    3. attrib: 文件属性修改,如时间、权限
    4. delete: 文件或目录删除
    5. create: 文件或目录创建