faith丶

导航

inotify+rsync实时同步文件

###

1.前提

部署rsync服务

2.安装inotify

(1) 部署inotify
#说明:inotify-tools软件需要依赖epel源
yum install -y inotify-tools

(2)查看安装好的服务都安装了什么信息
rpm -ql inotify-tools
/usr/bin/inotifywait       *****
#在被监控的文件或目录上等待特定文件系统事件(open close delete等)发生,执行后处于阻塞状态,适合在shell脚本中使用   
#通过此命令,实现对目录或文件的监控  
/usr/bin/inotifywatch  
收集被监控的文件系统使用的统计数据,指文件系统事件发生的次数统计。
统计文件数据信息变化的数量

(3)inotfy部署条件参数/proc/sys/fs/inotify/三个重要文件说明
ll /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 Oct 13 08:21 max_queued_events
-rw-r--r-- 1 root root 0 Oct 13 08:21 max_user_instances
-rw-r--r-- 1 root root 0 Oct 13 08:21 max_user_watches

(4)实时同步服务inotify优化信息
max_user_watches  --- 设置inotifywait或inotifywatch命令可以监视的文件数量(单进程)默认数值8192。
max_user_instances  --- 设置每个用户可以运行的inotifywait或inotifywatch命令的进程数 默认数值128
max_queued_events --- 设置inotify实例事件(event)队列可容纳的事件数量默认数值16384
说明:以上文件说明信息可以通过man proc获取得到以上参数的文件默认数值信息

3.inotify使用方法

inotifywait -mrq /data  --format '%w%f'  -e create,delete,close_write,moved_to
参数说明 : 
  -m   是要持续监视变化。
  -r   使用递归形式监视目录。
  -q   减少冗余信息,只打印出需要的信息。
  -e   指定要监视的事件列表。
  --format  指定文件变化的详细信息。
  --timefmt 是指定时间的输出格式。
  %T时间;
  %w触发事件文件所在绝对路径;
  %f触发事件文件名称;
  %e触发的事件名称;
Events: 事件
  access        file or directory contents were read 文件或目录被(访问)读取r
  modify        file or directory contents were written 文件或目录被写入w
  attrib        file or directory attributes changed 文件或目录属性变更【理由:chmod更改属性】
  close_write   file or directory closed, after being opened in writeable mode 文件或目录被写关闭【理由:文件内容被更改】
  close_nowrite file or directory closed, after being opened in read-only mode 文件或目录以只读方式打开后关闭
  close         file or directory closed, regardless of read/write mode 文件或目录被用编辑器(不管是读或写)关闭
  open          file or directory opened 文件或目录被用编辑器打开
  moved_to      file or directory moved to watched directory 文件或目录被移动进来【理由:mv目录内重命名】
  moved_from    file or directory moved from watched directory 文件或目录被移动出去
  move          file or directory moved to or from watched directory 文件或目录不管是移出或移进
  create        file or directory created within watched directory 文件或目录被创建【理由:mkdir创建目录】
  delete        file or directory deleted within watched directory 文件或目录被删除【理由:rm删除】
  delete_self   file or directory was deleted 文件或目录自删除
  unmount       file system containing file or directory unmounted 文件系统取消挂载

4.编写脚本,执行

(1)编写脚本
###注释:while read line是一次性将文件信息读入并赋值给变量line ,while中使用重定向机制,文件中的所有信息都被读入并重定向给了整个while 语句中的line 变量。
[root@nfs01 ~]# vim /server/scripts/inotify.sh 
#!/bin/sh                                                    
inotifywait
-mrq /data --format '%w%f' -e create,delete,close_write,moved_to|\ while read line do rsync -avPz --delete /data/ rsync_backup@172.16.1.41::backup --password-file=/etc/rsync.password done (2)执行脚本 sh /server/scripts/inotify.sh & nohup sh /server/scripts/inotify.sh &

 

###

posted on 2021-01-25 13:49  faith丶  阅读(188)  评论(0编辑  收藏  举报