---
title: "linux 利用inotify-tools配合rsync实时同步文件"
author: "xiaojiit"
date: "2013-01-27T15:03:18Z"
tags: []
categories: ["操作系统"]
slug: "linux-inotify-tools-rsync"
draft: false
lastmod: "2013-01-27T15:29:08Z"
id: 1776333
url: "https://sharejava.iteye.com/blog/1776333"
---

1、安装inotify-tools 工具

      为能在shell下使用inotify特性，需要安装inotify-tools

      下载地址：http://inotify-tools.sourceforge.net/  
      编译安装  
          ./configure  
          make  
          make install

 

2、编写自动监听脚本 

   

shell 写道

#!/bin/bash  
###########################  
\# 在这里配置本地文件夹,目标host,目标的rsync\_module。rsync\_module在同步机器的/etc/rsyncd.conf文件中配置  
\# 逗号前后不要有空格  
#sync\[0]='/tongbu,192.168.61.113,test' # localdir,host,rsync\_module  
#sync\[0]='/tongbu,192.168.61.195,test' # localdir,host,rsync\_module  
sync\[0]='/root,192.168.1.3,test'  
#sync\[1]='/tongbu,192.168.61.195,test1'  
###########################

for item in ${sync\[@]}; do

dir=\`echo $item | awk -F"," '{print $1}'\`  
host=\`echo $item | awk -F"," '{print $2}'\`  
module=\`echo $item | awk -F"," '{print $3}'\`

inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f %e' --event CLOSE\_WRITE,create,move,delete $dir | while read date time file event  
do  
#echo $event'-'$file  
case $event in  
MODIFY|CREATE|MOVE|MODIFY,ISDIR|CREATE,ISDIR|MODIFY,ISDIR)  
if \[ "${file: -4}" != '4913' ] && \[ "${file: -1}" != '~' ]; then  
#cmd="rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd-clinet.pass $dir root@$host::$module"  
cmd="rsync -vzrtopg --progress --delete $dir @$host::$module"  
#echo $cmd  
$cmd  
fi  
;;

MOVED\_FROM|MOVED\_FROM,ISDIR|DELETE|DELETE,ISDIR)  
if \[ "${file: -4}" != '4913' ] && \[ "${file: -1}" != '~' ]; then  
#cmd="rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd-clinet.pass $dir root@$host::$module"  
cmd="rsync -vzrtopg --progress --delete $dir @$host::$module"  
#cho $cmd  
$cmd  
fi  
;;  
esac  
done &  
done

 3、将脚本加入启动项：

     添加到rc.local中，可在系统启动时，启动监听。