2

linux实战之inotifywait、rsync实现文件监控

 1 year ago
source link: https://blog.51cto.com/u_12907475/5470085
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Linux文件监控

有时候我们常需要当文件变化的时候便触发某些脚本操作,比如说有文件更新了就同步文件到远程机器。在实现这个操作上,主要用到两个工具,一个是rsync,一个是inotifywait 。inotifywait的作用是监控文件夹变化,rsync是用来同步,可同步到本机的其他目录或者远程服务器上。

安装rsync

wget http://rsync.samba.org/ftp/rsync/src/rsync-3.1.1.tar.gz
tar zxvf rsync-3.1.1.tar.gz 
./configure -prefix=/usr/local/rsync-3.1.1
make
make install

安装inotifywait

wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
tar zxvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure
make
make install

创建并运行脚本

新建脚本inotifywait.sh 并输入以下内容

#!/bin/bash
export CNROMS_SRC=/home/ftpuser/gri/   # 同步的路径,请根据实际情况修改
inotifywait --exclude '\.(part|swp)' -r -mq -e  modify,move_self,create,delete,move,close_write $CNROMS_SRC |
  while read event;
    do
    rsync -vazu --progress  --password-file=/etc/rsyncd_rsync.secret  /home/ftpuser/gri/sla  [email protected]::gri ##这里执行同步的命令,可以改为其他的命令

  done

然后执行下面命令,会在后台执行监控:

nohup sh inotifywait.sh > /dev/null 2>&1

rsync

-v:给出哪些文件正在被传输的信息,还会在传输结束时给出一个简要总结信息。两个"-v"选项(-vv)将给出哪些文件被忽略,并且在传输结束时给出更详细的信息
-a:该选项等价于"-rlptgoD"选项的组合。它表示使用归档模式并保留几乎所有属性(明显遗漏了"-H"选项)。
-z:使用该选项,rsync将对发送给目标主机的文件数据(file data)进行压缩,这可以减少传输的数据量——在某些缓慢的连接中可能比较适用。
-u:该选项将强制忽略在目标路径下已存在且修改时间比源文件更新的文件。(如果已存在的目标文件的修改时间和源文件相同,则只在文件大小不同时才会更新)
–progress:该选项告诉rsync显示传输进度信息,这是给那些无聊的用户看的。它隐含了"–verbose"。
–password-file:该选项让rsync在连接rsync daemon时从密码文件中获取密码。密码文件必须可读。该文件中只有第一行是rsync将读取的密码,其他所有行都自动忽略。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK