rsync & inotifywait & sersync

 

rsync Options:

-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 打印版本信息

 

server:

use chroot = false  # 如果"use chroot"指定为true,那么rsync在传输文件以前首先chroot到path参数所指定的目录下。这样做的原因是实现额外的安全防护,但是缺点是需要root权限,并且不能备份指向外部的符号连接所指向的目录文件。默认情况下chroot值为true。
strict modes = false # 该选项指定是否监测密码文件的权限,如果该选项值为true那么密码文件只能被rsync服务器运行身份的用户访问,其他任何用户不可以访问该文件。默认值为true
uid = root # 运行RSYNC守护进程的用户,该选项指定当该模块传输文件时守护进程应该具有的uid,配合gid选项使用可以确定哪些可以访问怎么样的文件权限,默认值是"nobody"。
gid = root # 运行RSYNC守护进程的组
log file = /var/log/rsyncd.log # 不指定,发送至syslog
lock file = /var/run/rsyncd.lock
pid file = /var/run/rsyncd.pid
motd file = /etc/rsyncd.motd
reverse lookup = false # Controls whether the daemon performs a reverse lookup on the client’s IP address to determine its hostname
ignore errors
ignore nonreadable = yes # 指定rysnc服务器完全忽略那些用户没有访问权限的文件
transfer logging = yes # 记录传输日志
syslog facility = local5 # auth, authpriv, cron, daemon, ftp, kern, lpr, mail, news, security, sys-log, user, uucp, local0, local1, local2, local3,local4, local5, local6和local7。默认值是daemon。
hosts allow = * # 所有主机均可访问
timeout = 0 # 通过该选项可以覆盖客户指定的IP超时时间。通过该选项可以确保rsync服务器不会永远等待一个崩溃的客户端。超时单位为秒钟,0表示没有超时定义,这也是默认值。对于匿名rsync服务器来说,一个理想的数字是600。
host allow = 172.16.0.0/12 # 默认允许所有
host deny = *
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
exclude = lost+found,rpm # server端隐藏的文件或文件夹
read only = false # 该选项设定是否允许客户上载文件。如果为true那么任何上载请求都会失败,如果为false并且服务器目录读写权限允许那么上载是允许的。默认值为tru
write only = false
list = true # 是否允许显示改模块 rsync --password-file=/etc/rsyncd.secrets rsync://rsync@perpetual
auth users = rsync,rim # 认证的用户名,如果没有这行则表明是匿名,此用户与系统无关
secrets file = etc/rsyncd.secrets # rsync的密码文件路径
max connections = 0 # 指定该模块的最大并发连接数量以保护服务器,超过限制的连接请求将被告知随后再试。默认值是0,也就是没有限制

[cwRsync]
path = /cygdrive/d/u01/nc_backup/# 和linux不同的是windows的备份目录前面都要加/cygdrive
comment = 'rsync comment'

 

/etc/rsyncd.secrets

 

user1:password1
user2:password2

 

 

 

 

client:

client:

rsync --password-file=/etc/rsyncd.secrets rsync://rsync@perpetual:873/rod .
rsync --port 873 --password-file=/etc/rsyncd.secrets rsync@perpetual::rod .
rsync --password-file=/etc/rsyncd.secrets  --list-only rsync://rsync@perpetual:873/rod
rsync --password-file=/etc/rsyncd.secrets rsync://rsync@perpetual:873/rod/a .

echo password >> /etc/rsyncd.secrets


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

 

inotify:

yum install inotify-tools

 

Exercise:

inotifywait -mrq -e modify /root/a.txt | \
while read line;do
        if tail -1 /root/a.txt | grep uiop;then
                echo ppppppppppppp
        else
                echo mmmmmmmmmmmmmmm
        fi
done

 

First Edition:

inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir /root/p | \
while read line;do

        echo $line
        if echo $line|grep -i delete &> /dev/null;then
                echo "At `date +"%F %T"`: $line" >> /root/delete.log
        else
                rsync -avzP /root/p/ --delete --password-file=/etc/rsyncd.secrets rsync://rsync@perpetual/rod
        fi
done

delete记录日志,不触发同步

############### 注意/root/p 和 /root/p/ 的区别

 

Second Edition:

#!/bin/sh

watch_dir=/root/p/
dst=perpetual
inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir --timefmt '%Y-%m-%d %H:%M::%S' --format '%w%f:%e:%T' $watch_dir \
--exclude=".*.swp" | \
while read line;do
        # 记录删除和移走的文件
        if echo $line|grep -i -E "delete|moved_from" &> /dev/null;then
                echo "$line" >> /var/log/inotifywait_del.log
        fi

        # rsync
        rsync -avzP --delete --password-file=/etc/rsyncd.secrets --exclude="*.swp" --exclude="*.swx" $watch_dir rsync://rsync@$dst/rod

        if [ $? -eq 0 ];then
                echo "$watch_dir succeed"
        else
                echo "$watch_dir failed"
        fi
done

 

Best Practice:

#!/bin/env sh

###########################################################
#  description: inotify+rsync best practice               #
#  author     : cruces                                    #
#  blog       : www.ibm.com                               #
###########################################################


watch_dir=/root/p
dst=perpetual

function sersync(){
        rsync -avzP --delete --password-file=/etc/rsyncd.secrets --exclude="*.swp" --exclude="*.swx" $watch_dir rsync://rsync@$dst/rod
        return $?
}

# initial rsync to reduce events
sersync

inotifywait -mrq -e delete,close_write,moved_to,moved_from,isdir --timefmt '%Y-%m-%d %H:%M:%S' --format '%w%f:%e:%T' $watch_dir --exclude=".*.swp" \
--exclude='.*.swp' --exclude='.*.swx' >> /etc/inotifywait.log &


echo -e '\e[7;34mStart Monitoring\e[0m'
while true;do
        if [[ -s /etc/inotifywait.log ]];then
                grep -iE 'delete|moved_from' /etc/inotifywait.log >> /etc/inotify_away.log
                sersync
                if [[ $? -ne 0 ]];then
                        echo "$watch_dir rsync to $dst failed at `date +"%F %T"`" | \
                        mail -s 'inotifywait & rsync error has occurred' root@localhost
                fi

                cat /dev/null > /etc/inotifywait.log

                sersync
        else
                sleep 3
        fi
done

 

 

sersync:

wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/sersync/sersync2.5.4_64bit_binary_stable_final.tar.gz
tar xvzf sersync2.5.4_64bit_binary_stable_final.tar.gz
cp -a GNU-Linux-x86 /usr/local/sersync
echo "PATH=$PATH:/usr/local/sersync" > /etc/profile.d/sersync.sh
source /etc/profile.d/sersync

 

*.xml

<?xml version="1.0" encoding="ISO-8859-1"?>
<head version="2.5">
    <host hostip="localhost" port="8008"></host>
    <debug start="false"/>       # 是否开启调试模式,下面所有出现false和true的地方都分别表示关闭和开启的开关
    <fileSystem xfs="true"/>     # 监控的是否是xfs文件系统
    <filter start="true">        # 是否启用监控的筛选功能,筛选的文件将不被监控
        <exclude expression="(.*)\.svn"></exclude>
        <exclude expression="(.*)\.gz"></exclude>
        <exclude expression="^info/*"></exclude>
        <exclude expression="^static/*"></exclude>
        <exclude expression="(.*)\.rpm"></exclude>
    </filter>

    <inotify>                    # 监控的事件,默认监控的是delete/close_write/moved_from/moved_to/create folder
        <delete start="true"/>
        <createFolder start="true"/>
        <createFile start="false"/>
        <closeWrite start="true"/>
        <moveFrom start="true"/>
        <moveTo start="true"/>
        <attrib start="false"/>
        <modify start="false"/>
    </inotify>

    <sersync>                                    # rsync命令的配置段
        <localpath watch="/data/www">            # 同步的目录或文件,同inotify+rsync一样,建议同步目录
            <remote ip="perpetual" name="www"/>  # 目标地址和rsync daemon的模块名,所以远端要以daemon模式先运行好rsync
            <remote ip="exclamatory" name="www"/># 下面开启了ssh start,此时name为远程shell方式运行时的目标目录
            <!--<remote ip="172.16.10.5" name="/tmp/www"/>--> # 远程shell模式
            <!--<remote ip="192.168.8.40" name="tongbu"/>-->
        </localpath>

        <localpath watch="/data/bbs">
            <remote ip="perpetual" name="bbs"/>
            <remote ip="exclamatory" name="bbs"/>
        </localpath>

        <localpath watch="/data/blog">
            <remote ip="perpetual" name="blog"/>
            <remote ip="exclamatory" name="blog"/>
        </localpath>


        <rsync>                                  # 指定rsync选项
            <commonParams params="-artuz --delete"/>
            <auth start="true" users="rsync" passwordfile="/etc/rsyncd.passwd"/>
            <userDefinedPort start="false" port="874"/><!-- port=874 -->
            <timeout start="true" time="100"/><!-- timeout=100 -->
            <ssh start="false"/>                 # 是否使用远程shell模式而非rsync daemon运行rsync命令
        </rsync>

        # 错误重传
        <failLog path="/usr/local/sersync/logs/rsync_fail_log.sh" timeToExecute="60"/><!--default every 60mins execute once-->

        # 是否开启crontab功能
        <crontab start="false" schedule="600"><!--600mins-->
            <crontabfilter start="false">
                <exclude expression="*.php"></exclude>
                <exclude expression="info/*"></exclude>
            </crontabfilter>
        </crontab>


        <plugin start="false" name="command"/>
    </sersync>

    <plugin name="command">
        <param prefix="/bin/sh" suffix="" ignoreError="true"/>  <!--prefix /opt/tongbu/mmm.sh suffix-->
        <filter start="false">
            <include expression="(.*)\.php"/>
            <include expression="(.*)\.sh"/>
        </filter>
    </plugin>

    <plugin name="socket">
        <localpath watch="/opt/tongbu">
            <deshost ip="192.168.138.20" port="8009"/>
        </localpath>
    </plugin>
    <plugin name="refreshCDN">
        <localpath watch="/data0/htdocs/cms.xoyo.com/site/">
            <cdninfo domainname="ccms.chinacache.com" port="80" username="xxxx" passwd="xxxx"/>
            <sendurl base="http://pic.xoyo.com/cms"/>
            <regexurl regex="false" match="cms.xoyo.com/site([/a-zA-Z0-9]*).xoyo.com/images"/>
        </localpath>
    </plugin>
</head>

 

 

/usr/local/sersync/sersync2  -d -r -o /usr/local/sersync/confxml.xml

 

 

rsync --include  --exclude 规则:

使用-n --dryn-run  和  -i  itemize(列出清单)来进行调试
首选明确一点要同步多层次目录下的某些文件时,必须先同步其所有父目录

  1. 只写 var 这种的 可以同时匹配目录和文件, var/ 明确指出同步的是目录

     /var/log目录和 /var/log/log文件都被同步


     

     log/ 明确指出这是目录,只有目录被同步

    同时要注意src的格式, /var/log  &  /var/log/是不同的

  2. */ 的含义是所有目录
    rsync -rvni --include='*/' --exclude='*' /var/log /tmp

     

     可以看到/var/log目录(包括本身)的层次树都被同步了,和文件不同的是文件需要先同步其所有父目录


    rsync -rvni --include='*/' --exclude='*' /var/log/ /tmp

     

     此种方式就排除了 log目录本身 因为 /var/log/ 是不包含目录本身的

  3. rsync -rvni --include='log/*' --exclude='*' /var/log /tmp

     

     上面的错误是没有先创建log目录,即要先同步log目录

    rsync -rvni --include='log/' --include='log/*' --exclude='*' /var/log /tmp

     

     上面同步了log下的所有文件和一级子目录

     rsync -rvni --include='log/' --include='log/*/' --exclude='*' /var/log /tmp

     

     上面同步了log下的所有目录

    ok,如何同步log下的所有文件,排除一级子目录呢?
    我们只需要将--exclude='log/*/' 放到 --include='log/*'前面 就可以了

    rsync -rvni --include='log/' --exclude='log/*/' --include='log/*' --exclude='*' /var/log /tmp

     

     

  4. --include='toe' 同步toe文件和目录
    --include='toe/' 同步toe目录
    --include='toe/*' 同步toe下的所有文件和目录
    --exclude='*/' 排除所有目录
    --exclude='*' 排除所有文件和目录

     

  5. /var/log  /var/log/  这两种情况 /* 所指代意义不同,因为其 / 起始点不同
    rsync -nvri --include='/*' --exclude='*' /var/log /tmp #  / 下 只有 log

     

    rsync -nvri --include='/*' --exclude='*' /var/log/ /tmp   # / 起始于 /var/log/

     

     

  6. 只同步某个文件
    rsync -rvni --include='log/' --include='anaconda/' --include='syslog' --exclude='*' /var/log /tmp

     

     必须先将其父目录同步

  7. dst 目标 /tmp 和 /tmp/ 是没有区别的,但是src 带/是明确代表目录
  8. 递归定向同步特定文件夹
    当使用--include='log/journal/*' 这种格式的时候是不会进行递归的
    rsync -rvni --include='log/' --include='log/journal/' --include='log/journal/*' --exclude='*' /var/log /tmp

     

     只同步了 log/journal/下的文件夹和文件,但没有递归进去

    rsync -rvni --include='log/' --include='log/journal/' --include='log/journal/*' --exclude='*/' --exclude='log/*' /var/log /tmp # 先排除所有目录(只有--include目录才会同步),再排除 / 下的所有文件(/ 依据 src而定)

     

     

     rsync -rvni --include='journal/' --include='journal/*' --exclude='*/' --exclude='/*' /var/log/ /tmp # src 为 /var/log/的情况

     

 

 

frequently asked questions:

 

  1. cwRsync虽然在Windows平台但是依然case sensitive

  2. -f --filter 过滤选项
    -f '+ */' 放行所有目录
    -f '- *'   禁止所有文件和目录
    -f '+ */' -f '- *' 只同步目录
  3. 我们一般是通过客户端返回的错误进行分析
    https://www.jb51.net/article/31920.htm
  4. Windows同步脚本
    net use S: \\${server_ip}\share_name password /usr:administrator
    rsync -avzuP --delete --stats /cygdrive/d/backup /cygdrive/s/backup
    pause
    net use S: /delete
    exit 0
 
常见错误:
  1. @ERROR: chdir failed
    rsync error: error starting client-server protocol (code 5) at main.c(1296) [sender=2.6.8]
    服务器日志(/var/log/rsyncd.log):
    rsync: chdir /backup failed: Permission denied (13)

    Server端没有目录或者没有权限

  2. @ERROR: auth failed on module
    rsync: connection unexpectedly closed (102 bytes read so far)
    rsync error: error in rsync protocol data stream (code 12) at io.c(165)
    服务器端日志将出现错误提示:
    2005/08/23 06:32:01 [8388] secrets file must not be other-accessible (see strict modes option)
    2005/08/23 06:32:01 [8388] continuing without secrets file
    2005/08/23 06:32:01 [8388] auth failed on module from documentserver
    服务器端rsyncd.secrets (用户:密码)<用户必须是系统用户,密码尽量不要为系统用户密码>
    客户端rsyncd.secrets (密码)<服务器端密码>

     

 

 

常用用法:

rsync -azv /home rsync://root@192.168.1.107/hadoop --password-file=/home/rsyncd.secrets

 

posted @ 2020-10-26 19:43  ascertain  阅读(199)  评论(0编辑  收藏  举报