linux实践——实现inotify+rsync实时同步系统

1、检测分发服务器系统是否满足需求,要求内核大于2.3

 uname -r #查看系统内核
 ll /proc/sys/fs/inotify/

  

如图则满足需求。

2、在分发服务器下载最新版并编译安装

cd  #回到用户目录
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 --prefix=/alidata/server/inotify/ #编译配置,这里是指定位置(你的文件目录)
make #编译
make install #安装
make clean #从源文件夹清除二进制对象等 
cd /alidata/server/inotify/bin
./inotifywait --help  #查看是否安装完成一般有错误上面几个步骤会有提示
./inotifywait -mrq --format '%Xe %w%f' -e modify,create,delete,attrib /alidata/tmp/ #m是开启监测,r递归目录,/alidata/tmp监测的目录 touch /alidata/tmp/test1 #新开个tty创建个文件会有如下图输出

#为方便使用可以选择设置 #设置系统环境变量,添加软连接 #echo "PATH=$PATH:/alidata/server/inotify/bin" >>/etc/profile.d/inotify.sh #source /etc/profile.d/inotify.sh #使设置立即生效 #echo "/alidata/server/inotify/lib" >/etc/ld.so.conf.d/inotify.conf && ldconfig #ln -s /alidata/server/inotify/include /usr/include/inotify

  

至此已经可以检测到分发服务器文件改动了。

3、编译安装rsync到内容分发服务器在这里充当客户端的角色

wget https://download.samba.org/pub/rsync/src/rs
tar zxvf rsync-3.1.2.tar.gz
cd rsync-3.1.2
 ./configure  --prefix=/alidata/server/rsync
make
make install

 接下来就是文件同步,检测到文件变动后主动向目标服务器推送,详情后面说。

4、编译安装rsync到目标服务器并启用服务

wget https://download.samba.org/pub/rsync/src/rs
tar zxvf rsync-3.1.2.tar.gz
cd rsync-3.1.2
 ./configure  --prefix=/alidata/server/rsync
make
make install

   添加主配置文件:  

nano /etc/rsyncd.conf

  复制以下代码

uid = root
gid = root
port = 873
use chroot = no
hosts allow = *
max connections = 3
motd file = /alidata/passwd/rsync/rsyncd.mot #问候语
pid file = /alidata/server/rsync/rsyncd.pid
lock file = /alidata/server/rsync/rsync.lock
log file = /alidata/log/rsync/rsyncd.log
transfer logging = yes #传输日志
ignore errors #忽略错误

[netho]
path = /alidata/tmp/rsynctest #同步路径
auth users = netho  #使用用户必须是服务器真实用户
secrets file = /alidata/passwd/rsync/rsyncd.pass #用户认证文件
list = no
read only = no #只读

  建立认证文件,我使用的是apache的认证工具生成的密码复杂一点嘛(嫌麻烦直接手动输入echo woshimima >/alidata/passwd/rsync/rsyncd.pass)

mkdir -p /alidata/passwd/rsycn 
htpasswd -cb /alidata/passwd/rsync/rsyncd.pass netho Netho123456789
chmod 600 /alidata/passwd/rsync/rsyncd.pass #为什么要这一步呢?和strict modes =yes/no有关系么,没时间实验了,擦

  设定rsyncd.motd 文件;   

nano /alidata/passwd/rsync/rsyncd.mot

  复制以下代码

++++++++++++++++++++++++++++++++++++++++++++++
  Welcome to use the  rsync services!
           2002------2009
  ++++++++++++++++++++++++++++++++++++++++++++++

启动rsync服务:

cd /alidata/server/rsync/bin
./rsync  --daemon --config=/etc/rsyncd.conf &

打开指定端口

ufw allow 873/tcp

测试链接

ps -ef |grep rsync #进程
netstat -anop | grep rsync #端口信息
./rsync -rdt rsync://127.0.0.1:873/ #看到下图我们设置的欢迎信息(mot)说明启动成功服务正常

  

  怎么停止???我也不知道啦^_^ 

为了方便我们使用脚本来管理将其加入service

touch /etc/init.d/rsyncd
chmod +x /etc/init.d/rsyncd
nano /etc/init.d/rsyncd

 复制以下代码

#!/bin/bash 
# description: rsync server
# processname: rsyncd
 
status1=$(ps -ef | egrep "rsync --daemon.*rsyncd.conf" | grep -v 'grep') 
pidfile="/alidata/server/rsync/rsyncd.pid" 
rsync="/alidata/server/rsync/bin/rsync"
start_rsync="${rsync} --daemon --config=/etc/rsyncd.conf" 
 
function rsyncstart() { 
 
    if [ "${status1}X" == "X" ];then
        ${start_rsync}    
        status2=$(ps -ef | egrep "rsync --daemon.*rsyncd.conf" | grep -v 'grep') 
         
        if [  "${status2}X" != "X"  ];then 
             
            echo "rsync service start.......OK" 
             
        fi 
 
    else 
 
        echo "rsync service is running !"    
 
    fi 
} 
 
function rsyncstop() { 
 
    if [ "${status1}X" != "X" ];then 
     
        kill -9 $(cat $pidfile)
        rm -f $pidfile
 
        status2=$(ps -ef | egrep "rsync --daemon.*rsyncd.conf" | grep -v 'grep') 
 
        if [ "${statusw2}X" == "X" ];then 
             
            echo "rsync service stop.......OK" 
        fi 
    else 
 
        echo "rsync service is not running !"    
 
    fi 
} 
 
 
function rsyncstatus() { 
 
 
    if [ "${status1}X" != "X" ];then 
 
        echo "rsync service is running !"   
     
    else 
 
         echo "rsync service is not running !"  
 
    fi 
 
} 
 
function rsyncrestart() { 
 
    if [ "${status1}X" == "X" ];then
 
          echo "rsync service is not running..." 
 
          rsyncstart 
 
      else
 
          rsyncstop
          rsync --daemon --config=/usr/local/server/rsync/etc/rsyncd.conf
          status2=$(ps -ef | egrep "rsync --daemon.*rsyncd.conf" | grep -v 'grep')          
 
        if [  "${status2}X" != "X"  ];then              
    
            echo "rsync service start.......OK"       
 
        else 
 
            echo "rsync service is not running !" 
 
        fi
 
    fi  
}  
 
case "$1" in 
 
        "start") 
               rsyncstart 
                ;; 
 
        "stop") 
               rsyncstop 
                ;; 
 
        "status") 
               rsyncstatus 
               ;; 
 
        "restart") 
               rsyncrestart
               ;; 
 
        *) 
          echo 
                echo  "Usage: $0 start|stop|restart|status" 
          echo 
esac
exit 0

备份

#! /bin/sh

### BEGIN INIT INFO
# Provides:          rsyncd
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Should-Start:      $named
# Default-Start:     2 3 4 5
# Default-Stop:
# Short-Description: fast remote file copy program daemon
# Description:       rsync is a program that allows files to be copied to and
#                    from remote machines in much the same way as rcp.
#                    This provides rsyncd daemon functionality.
### END INIT INFO

set -e

# /etc/init.d/rsync: start and stop the rsync daemon

DAEMON=/usr/bin/rsync
RSYNC_ENABLE=false
RSYNC_OPTS=''
RSYNC_DEFAULTS_FILE=/etc/default/rsync
RSYNC_CONFIG_FILE=/etc/rsyncd.conf
RSYNC_PID_FILE=/var/run/rsync.pid
RSYNC_NICE_PARM=''
RSYNC_IONICE_PARM=''

test -x $DAEMON || exit 0

. /lib/lsb/init-functions

if [ -s $RSYNC_DEFAULTS_FILE ]; then
    . $RSYNC_DEFAULTS_FILE
    case "x$RSYNC_ENABLE" in
        xtrue|xfalse)   ;;
        xinetd)         exit 0
                        ;;
        *)              log_failure_msg "Value of RSYNC_ENABLE in $RSYNC_DEFAULTS_FILE must be either 'true' or 'false';"
                        log_failure_msg "not starting rsync daemon."
                        exit 1
                        ;;
    esac
    case "x$RSYNC_NICE" in
        x[0-9])         RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
        x1[0-9])        RSYNC_NICE_PARM="--nicelevel $RSYNC_NICE";;
        x)              ;;
        *)              log_warning_msg "Value of RSYNC_NICE in $RSYNC_DEFAULTS_FILE must be a value between 0 and 19 (inclusive);"
                        log_warning_msg "ignoring RSYNC_NICE now."
                        ;;
    esac
    case "x$RSYNC_IONICE" in
        x-c[123]*)      RSYNC_IONICE_PARM="$RSYNC_IONICE";;
        x)              ;;
        *)              log_warning_msg "Value of RSYNC_IONICE in $RSYNC_DEFAULTS_FILE must be -c1, -c2 or -c3;"
                        log_warning_msg "ignoring RSYNC_IONICE now."
                        ;;
    esac
fi

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

rsync_start() {
    if [ ! -s "$RSYNC_CONFIG_FILE" ]; then
        log_failure_msg "missing or empty config file $RSYNC_CONFIG_FILE"
        log_end_msg 1
        exit 0
    fi
    # See ionice(1)
    if [ -n "$RSYNC_IONICE_PARM" ] && [ -x /usr/bin/ionice ] &&
        /usr/bin/ionice "$RSYNC_IONICE_PARM" true 2>/dev/null; then
        /usr/bin/ionice "$RSYNC_IONICE_PARM" -p$$ > /dev/null 2>&1
    fi
    if start-stop-daemon --start --quiet --background 
        --pidfile $RSYNC_PID_FILE --make-pidfile 
        $RSYNC_NICE_PARM --exec $DAEMON 
        -- --no-detach --daemon --config "$RSYNC_CONFIG_FILE" $RSYNC_OPTS
    then
        rc=0
        sleep 1
        if ! kill -0 $(cat $RSYNC_PID_FILE) >/dev/null 2>&1; then
            log_failure_msg "rsync daemon failed to start"
            rc=1
        fi
    else
        rc=1
    fi
    if [ $rc -eq 0 ]; then
        log_end_msg 0
    else
        log_end_msg 1
        rm -f $RSYNC_PID_FILE
    fi
} # rsync_start


case "$1" in
  start)
        if "$RSYNC_ENABLE"; then
            log_daemon_msg "Starting rsync daemon" "rsync"
            if [ -s $RSYNC_PID_FILE ] && kill -0 $(cat $RSYNC_PID_FILE) >/dev/null 2>&1; then
                log_progress_msg "apparently already running"
                log_end_msg 0
                exit 0
            fi
            rsync_start
        else
            if [ -s "$RSYNC_CONFIG_FILE" ]; then
                [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in $RSYNC_DEFAULTS_FILE, not starting..."
            fi
        fi
        ;;
  stop)
        log_daemon_msg "Stopping rsync daemon" "rsync"
        start-stop-daemon --stop --quiet --oknodo --pidfile $RSYNC_PID_FILE
        log_end_msg $?
        rm -f $RSYNC_PID_FILE
        ;;

  reload|force-reload)
        log_warning_msg "Reloading rsync daemon: not needed, as the daemon"
        log_warning_msg "re-reads the config file whenever a client connects."
        ;;

  restart)
        set +e
        if $RSYNC_ENABLE; then
            log_daemon_msg "Restarting rsync daemon" "rsync"
            if [ -s $RSYNC_PID_FILE ] && kill -0 $(cat $RSYNC_PID_FILE) >/dev/null 2>&1; then
                start-stop-daemon --stop --quiet --oknodo --pidfile $RSYNC_PID_FILE || true
                sleep 1
            else
                log_warning_msg "rsync daemon not running, attempting to start."
                rm -f $RSYNC_PID_FILE
            fi
            rsync_start
        else
            if [ -s "$RSYNC_CONFIG_FILE" ]; then
                [ "$VERBOSE" != no ] && log_warning_msg "rsync daemon not enabled in $RSYNC_DEFAULTS_FILE, not starting..."
            fi
        fi
        ;;

  status)
        status_of_proc -p $RSYNC_PID_FILE "$DAEMON" rsync
        exit $? # notreached due to set -e
        ;;
  *)
        echo "Usage: /etc/init.d/rsync {start|stop|reload|force-reload|restart|status}"
        exit 1
esac

exit 0

  设置开机启动

echo "/etc/init.d/rsyncd start" >>/etc/rc.local

   

5、目标服务器配好以后,在内容分发服务器上编写监控文件变化启动同步的脚本rstnc-inotify.sh

#!/bin/bash
server=/alidata/server/
rsync=${server}rsync/bin/rsync
inotify=${server}inotify/bin
src=/alidata/tmp/mubiao/
log=/alidata/log/rsync-inotify.log # 需要同步的源路径 des=netho # 目标服务器上配置中[]里的名称。 rsync_passwd_file=/alidata/passwd/rsync/rsyncd.pass # rsync验证的密码文件 ip=127.0.0.1 # 目标服务器1 ip1=192.168.0.19 # 目标服务器2 user=netho # rsync --daemon定义的验证用户名 cd ${src} # 此方法中,由于rsync同步的特性,这里必须要先cd到源目录, # inotify再监听 ./ 才能rsync同步后目录结构一致, ${inotify}/inotifywait -mrq --format '%Xe %w%f' -e modify,create,delete,attrib,close_write,move ./ | while read file # 把监控到有发生更改的文件路径列表循环 do INO_EVENT=$(echo $file | awk '{print $1}') # 把inotify输出切割 把事件类型部分赋值给INO_EVENT INO_FILE=$(echo $file | awk '{print $2}') # 把inotify输出切割 把文件路径部分赋值给INO_FILE echo "-------------------------------$(date)------------------------------------">> ${log} 2>&1 echo $file >> ${log} 2>&1 # 增加、修改、写入完成、移动进事件 # 增、改放在同一个判断,因为他们都肯定是针对文件的操作,即使是新建目录,要同步的也只是一个空目录,不会影响速度。 if [[ $INO_EVENT =~ 'CREATE' ]] || [[ $INO_EVENT =~ 'MODIFY' ]] || [[ $INO_EVENT =~ 'CLOSE_WRITE' ]] || [[ $INO_EVENT =~ 'MOVED_TO' ]] # 判断事件类型 then echo 'CREATE or MODIFY or CLOSE_WRITE or MOVED_TO' >> ${log} 2>&1 # ${rsync} -avzcR --port 3375 --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip1}::${des} && # INO_FILE变量代表路径哦 -c校验文件内容 ${rsync} -avzcR --port 3375 --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip}::${des} # 仔细看 上面的rsync同步命令 源是用了$(dirname ${INO_FILE})变liang # 即每次只针对性的同步发生改变的文件的目录(只同步目标文件的方法在生产环境的某些极端环境下会漏文件 #现在可以在不漏文件下也有不错的速度 做到平衡) 然后用-R参数把源的目录结构递归到目标后面 保证目录结构一致性 fi #删除、移动出事件 if [[ $INO_EVENT =~ 'DELETE' ]] || [[ $INO_EVENT =~ 'MOVED_FROM' ]] then echo 'DELETE or MOVED_FROM' >> ${log} 2>&1 #${rsync} -avzR --delete --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip1}::${des} && ${rsync} -avzR --delete --port 3375 --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip}::${des} # 看rsync命令 如果直接同步已删除的路径${INO_FILE}会报no such or directory错误 所以这里同步的源是被删文件或目录的上一级路径,         # 并加上--delete来删除目标上有而源中没有的文件,这里不能做到指定文件删除,如果删除的路径越靠近根,则同步的目录月多,同步删除的操作就越花时间。这里有更好方法的同学,欢迎交流。 fi #修改属性事件 指 touch chgrp chmod chown等操作 if [[ $INO_EVENT =~ 'ATTRIB' ]] then echo 'ATTRIB' if [ ! -d "$INO_FILE" ] # 如果修改属性的是目录 则不同步,因为同步目录会发生递归扫描,等此目录下的文件发生同步时,rsync会顺带更新此目录。 then # ${rsync} -avzcR --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip1}::${des} && ${rsync} -avzcR --port 3375 --password-file=${rsync_passwd_file} $(dirname ${INO_FILE}) ${user}@${ip}::${des} fi fi done

    参考http://www.ttlsa.com/web/let-infotify-rsync-fast/

chmod +x ./rsync-inotify.sh #赋予执行权限
./rsync-inotify.sh & #后台执行
echo  "/alidata/netho/rsync-inotify.sh &">>/etc/rc.local

  为防止脚本出现问题设置定时方案

crontab -e * */2 * * * rsync -avz --password-file=你的路径 /同步路径/ user@ip::方括号里的名称 

  

附:

rsync 的命令格式可以为以下六种:

  rsync [OPTION]... SRC DEST

  rsync [OPTION]... SRC [USER@]HOST:DEST

  rsync [OPTION]... [USER@]HOST:SRC DEST

  rsync [OPTION]... [USER@]HOST::SRC DEST

  rsync [OPTION]... SRC [USER@]HOST::DEST

  rsync [OPTION]... rsync://[USER@]HOST[:PORT]/SRC [DEST]

  对应于以上六种命令格式, rsync 有六种不同的工作模式:

  1) 拷贝本地文件。当 SRC 和 DES 路径信息都不包含有单个冒号 ":" 分隔符时就启动这种工作模式。

  2) 使用一个远程 shell 程序 ( 如 rsh 、 ssh) 来实现将本地机器的内容拷贝到远程机器。当 DST 路径地址包含单个冒号 ":" 分隔符时启动该模式。

  3) 使用一个远程 shell 程序 ( 如 rsh 、 ssh) 来实现将远程机器的内容拷贝到本地机器。当 SRC 地址路径包含单个冒号 ":" 分隔符时启动该模式。

  4) 从远程 rsync 服务器中拷贝文件到本地机。当 SRC 路径信息包含 "::" 分隔符时启动该模式。

  5) 从本地机器拷贝文件到远程 rsync 服务器中。当 DST 路径信息包含 "::" 分隔符时启动该模式。

  6) 列远程机的文件列表。这类似于 rsync 传输,不过只要在命令中省略掉本地机信息即可。

参数说明

-v, --verbose  详细模式输出
-q, --quiet 精简输出模式
-c, --checksum 打开校验开关,强制对文件传输进行校验
-a, --archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD
-r, --recursive 对子目录以递归模式处理
-R, --relative 使用相对路径信息
-b, --backup 创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix选项来指定不同的备份文件前缀。
--backup-dir 将备份文件(如~filename)存放在在目录下。
-suffix=SUFFIX 定义备份文件前缀
-u, --update 仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件。(不覆盖更新的文件)
-l, --links 保留软链结
-L, --copy-links 想对待常规文件一样处理软链结
--copy-unsafe-links 仅仅拷贝指向SRC路径目录树以外的链结
--safe-links 忽略指向SRC路径目录树以外的链结
-H, --hard-links 保留硬链结     -p, --perms 保持文件权限
-o, --owner 保持文件属主信息     -g, --group 保持文件属组信息
-D, --devices 保持设备文件信息    -t, --times 保持文件时间信息
-S, --sparse 对稀疏文件进行特殊处理以节省DST的空间
-n, --dry-run现实哪些文件将被传输
-W, --whole-file 拷贝文件,不进行增量检测
-x, --one-file-system 不要跨越文件系统边界
-B, --block-size=SIZE 检验算法使用的块尺寸,默认是700字节
-e, --rsh=COMMAND 指定使用rsh、ssh方式进行数据同步
--rsync-path=PATH 指定远程服务器上的rsync命令所在路径信息
-C, --cvs-exclude 使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件
--existing 仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件
--delete 删除那些DST中SRC没有的文件
--delete-excluded 同样删除接收端那些被该选项指定排除的文件
--delete-after 传输结束以后再删除
--ignore-errors 及时出现IO错误也进行删除
--max-delete=NUM 最多删除NUM个文件
--partial 保留那些因故没有完全传输的文件,以是加快随后的再次传输
--force 强制删除目录,即使不为空
--numeric-ids 不将数字的用户和组ID匹配为用户名和组名
--timeout=TIME IP超时时间,单位为秒
-I, --ignore-times 不跳过那些有同样的时间和长度的文件
--size-only 当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间
--modify-window=NUM 决定文件是否时间相同时使用的时间戳窗口,默认为0
-T --temp-dir=DIR 在DIR中创建临时文件
--compare-dest=DIR 同样比较DIR中的文件来决定是否需要备份
-P 等同于 --partial
--progress 显示备份过程
-z, --compress 对备份的文件在传输时进行压缩处理
--exclude=PATTERN 指定排除不需要传输的文件模式
--include=PATTERN 指定不排除而需要传输的文件模式
--exclude-from=FILE 排除FILE中指定模式的文件
--include-from=FILE 不排除FILE指定模式匹配的文件
--version 打印版本信息
--address 绑定到特定的地址
--config=FILE 指定其他的配置文件,不使用默认的rsyncd.conf文件
--port=PORT 指定其他的rsync服务端口
--blocking-io 对远程shell使用阻塞IO
-stats 给出某些文件的传输状态
--progress 在传输时现实传输过程
--log-format=formAT 指定日志文件格式
--password-file=FILE 从FILE中得到密码
--bwlimit=KBPS 限制I/O带宽,KBytes per second      -h, --help 显示帮助信息

rsync client配置

原文地址:https://www.cnblogs.com/perfectzhang/p/5648413.html