linux_inotify

什么是inotify?

  拥有强大、粒细粒度、异步文件系统事件监控机制,监控文件系统中添加、删除、修改、移动等各种事件

  版本支持: 内核 2.6.13以上版本,inotify-tools 是实施监控的软件

  同类软件: 国人 周洋 在金山公司开发sersync

inotify环境搭建

  1. rsync服务器 rsync --daemon 已经搭建

  2. 检查客户端是否支持

uname -r                             # 检查内核版本是否大于2.6.13

ls -l /proc/sys/fs/inotify        # 检查是否有这个目录,没有支持不了

rpm -aq inotify-tools            # 检查软件是否安装

# 没安装通过 yum install -y inotify-tools 安装

# 如果这个安装不了,安装阿里的epel源

# rpm -ivh https://mirrors.aliyun.com/epel/epel-release-latest-6.noarch.rpm

  3. 这个软件安装了两个命令 inotifywait 和 inotifywatch

这两个命令有什么区别?

       inotifywait

    在被监控的文件或目录上等待文件系统事件,执行后处于堵塞状态,适合在shell脚本中

  重要的参数: man inotifywait

         -m                 # 始终保持事件监听状态

         -e                  # 指定文件系统事件, close_write 关闭写

                              # 写文件过程: 打开文件,写文件,关闭文件

         -r                   # 递归查询目录

         -q                  # 打印很少信息,只打印监控事件的信息

         --timefmt       # 格式化时间显示 %y/%m%d %H:%M

         --format        # %T %w%f   显示更改文件名格式

  inotifywatch:

    统计文件系统时间发生次数,做统计

inotify简单使用
       1. 监控 /data目录

inotifywait -mrq --timefmt '%Y/%m/%d %H:%M' --format '%T %w%f' -e create /data/

# 这个只监控 create
#  delete 删除,删除并不需要打开文件; close_write 追加、修改文件、新增文件

       2. 往 /data 目录下写文件,将会看到输出

如何做实时备份?

       当 inotify 监控到目录触发事件,然后触发 rsync备份

       写一个脚本

mkdir /server/scripts -p             # 创建脚本目录
cd /server/scripts

vim realtime_rsync_nfs.sh        # 创建实时备份脚本

 

#!/bin/bash
# realtime rsync /data to backup
# master beimenchuixue

monitor_dir=/data/
backup_ip=172.16.1.15
login_user=backup_rsync
moudel_name=backup
rsync_passwd_file=/etc/rsync.password

/usr/bin/inotifywait -mrq --format '%w%f' -e create,close_write,delete $monitor_dir 
|while read file
do
/usr/bin/rsync -avz $monitor_dir --delete $login_user@$backup_ip::$moudel_name --password-file=$rsync_passwd_file
done

  

sh -x realtime_rsync_nfs.sh      # 测试

  

NFS备份可以考虑 --delete 方式,要求无差异备份

还有个命令也可以检测目录变化 watch

 

原文地址:https://www.cnblogs.com/2bjiujiu/p/8098756.html