Linux之rsync同步工具介绍+inotify同步

1.rsync介绍

  Rsync是一款开源的、快速的、多功能的、可实现全量及增量的本地或远程数据同步备份的优秀工具。Rsync软件适用于unix/linux/windows等多种操做平台。
  rsync,remote synchronize顾名思意就知道它是一款实现远程同步功能的软件,它在同步文件的同时,能够保持原来文件的权限、时间、软硬连接等附加信息。 rsync是用 “rsync 算法”提供了一个客户机和远程文件服务器的文件同步的快速方法,并且能够经过ssh方式来传输文件,这样其保密性也很是好,另外它仍是免费的软件。rsync官方文档(http://www.samba.org/ftp/rsync/rsync.htmlhtml

    rsync 特性(Some of the additional features of rsync are)

  • support for copying links, devices, owners, groups, and permissions(支持拷贝特殊文件如连接文件,设备等)
  • exclude and exclude-from options similar to GNU tar  (能够有排除指定文件或目录同步的功能,至关于打包命令tar的排除功能)
  • a CVS exclude mode for ignoring the same files that CVS would ignore(能够作到保持原文件或目录的权限,时间,软硬连接,属主、组等全部属性均不改变-p)
  • can use any transparent remote shell, including ssh or rsh(可实现增量同步,即只同步发生变化的数据,所以数据传输效率很高)
  • does not require super-user privileges(可使用rcp、rsh、ssh等方式来配合传输文件(rsync自己不对数据加密))
  • pipelining of file transfers to minimize latency costs(能够经过socket(进程方式)传输文件和数据)
  • support for anonymous or authenticated rsync daemons (ideal for mirroring)(支持匿名的或认证(无需系统用户)的进程模式传输,可实现方便安全的进行数据备份及镜像)

  来源官网linux

2.rsync的工做方式

  1)单个主句本地之间数据传输(此时相似于cp命令)git

  rsync本地传送模式的语法是:rsync [option...] src...[dest]github

  rsync为同步的命令,[option]为同步时的参数选项,src为源,即待拷的分区,文件或者目录等,[dest]为目的分区文件或者目录等web

ll  /data                <#删除前看一下
midir /null                <#建立一个空目录 rsync -r --delete /null /data/
ll  /data                <#删除完后看一下

  2)借助rcp,ssh等通道传输数据(此时相似于scp命令)算法

ssh-key中的scp回顾shell

scp -P 521 -rp -- /etc/hosts king@192.168.17: /tmp   <# -P 跟端口号    用户名@ ip  :目标文件

 rsync借助ssh通道拉取vim

rsync -avzP -e ‘ssh -p 22’ king@192.168.17:/opt /tmp <#-e 'ssh -p 22'表示经过ssh通道传送数据,-p22可略

 3)以守护进程(socket)的方式传输数据(这个是rsync自身的重要功能)windows

3.rsync命令使用,参数说明

  -v, --verbose   详细模式输出
  -z, --compress   对备份的文件在传输时进行压缩处理
  -a, --archive    归档模式,表示以递归方式传输文件,并保持全部文件属性,等于-rlptgoD
  -r, --recursive     对子目录以递归模式处理
  -t, --times      保持文件时间信息
  -o, --owner    保持文件属主信息
  -g, --group     保持文件属组信息
  -p, --perms     保持文件权限
  -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     保留硬链结
  -q, --quiet      精简输出模式
  -D, --devices      保持设备文件信息
  -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         显示备份过程
  --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        显示帮助信息
  不少对吧?简单工做中我就只用过avz,哈哈哈安全

4.rsync服务端,客户端安装配置  

 1)服务端安装配置

以守护进程(socket)的方式传输数据

[king@rsyncserver ~]$ rpm -qa rsync   #查看是否安装rsync rsync-3.0.6-9.el6_4.1.x86_64 [king@rsyncserver ~]$ vim /etc/rsyncd.conf   #/etc/rsyncd.conf默认是不存在的,因此咱们要建立它并编辑它 #rsync_config_______________start ##rsyncd.conf start## uid = rsync                    #rsync使用的用户,缺省uid为-2,一般为 nobody gid = rsync                    #rsync使用的组(用户所在的组)缺省gid为-2,一般为nobody use chroot = no                  max connections = 200              #设置最大的链接数,默认为0,就是无限制,负值为关闭这个模块 timeout = 60                   #默认为0,链接超时, pid file = /var/run/rsyncd.pid         #rsync daemon启动后将其进程PID写入此文件 lock file = /var/run/rsync.lock         #锁的机制 log file = /var/log/rsyncd.log         #日志配置文件,报错咱们查看他它 [king]                       #用户模块          path = /king/                   #用户共享的文件 ignore errors                   #错误忽略(i/o) read only = false                 #指定客户端是否能够上传文件,默认对全部模块都为true list = false                    #不显示列表 hosts allow = 192.168.1.7/24          #指定能够联系的客户端用户名和ip,address/mask hosts deny = 0.0.0.0/32             #默认是没哟 auth users = rsync_backup            #auth users指定以空格或者, 分隔的用户可使用那些模块 secrets file = /etc/rsync.password      #secrets file 指定用户名和密码的文件 格式 用户名:密码 #rsync_config_______________end ~ [root@rsyncserver /]# chown -R rsync.rsync king/ #建立共享目录,并让rsync用户能够管理king [root@rsyncserver ~]# chmod 600 /etc/rsync.password       #用户密码文件只能是600 [root@rsyncserver king]# ls -lh /etc/rsync.password -rw-------. 1 root root 19 9月 21 10:15 /etc/rsync.password [root@rsyncserver ~]# cat /etc/rsync.password #查看用户密码文件,注意其格式 rsync_backup:king [root@rsyncserver ~]# rsync --daemon #启动rsync服务,若是想要重启服务的话,先用pkill rsync杀掉进程而后再执行此操做 [root@rsyncserver ~]# ps -ef|grep rsync|grep -v grep root 1670     1  0 13:56 ?        00:00:00 rsync --daemon 注意:要关闭防火墙和selinux [king@rsyncserver .ssh]$ sudo /etc/init.d/iptables stop [king@rsyncserver .ssh]$ sudo getenforce Enforcing [king@rsyncserver .ssh]$ sudo setenforce 0 [kingy@rsyncserver .ssh]$ getenforce Permissive

  2)客户端安装配置

[root@rsyncclient ~]# rpm -qa rsync rsync-3.0.6-9.el6_4.1.x86_64 [root@rsyncclient ~]# vim /etc/rsync.password [root@rsyncclient ~]# chmod 600 /etc/rsync.password [root@rsyncclient ~]# useradd -s /sbin/nologin rsync [root@rsyncclient ~]# cat /etc/rsync.password king

 3)同步

 Local: rsync [OPTION...] SRC... [DEST] Access via remote shell: Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST] Push: rsync [OPTION...] SRC... [USER@]HOST:DEST Access via rsync daemon: 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
pull: [root@rsyncclient ~]# rsync -avz rsync_backup@192.168.1.7::king /data --password-file=/etc/rsync.password receiving incremental file list ./ a b sent 105 bytes  received 224 bytes  658.00 bytes/sec total size is 8  speedup is 0.02 push: [root@rsyncclient ~]# rsync -avz   /data/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #注意/data后面有斜杠和没斜杠的区别:没有斜杠的话将目录一块同步,有斜杠的话只同步目录下面的内容。

5.--exclude参数

1)只排除一个文件不一样步

rsync -avz --exclude=1 rsync_backup@192.168.1.7::king /data/ --password-file=/etc/rsync.password

  --exclude= 文件名字  rsync_backup是你/etc/rsyncd.conf文件里配置的auth users = rsync_backup  @ip   king  是你/etc/rsyncd.conf文件里配置的[king],--password-file=/etc/rsync.password即为读取你的密码文件,注意你的密码文件权限必须是600,且格式必须是相似键值对的形式存在,(用户:密码)

2)排除多个文件不一样步

方法一: rsync -avz --exclude={1,2} /data1/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #{文件名字用逗号隔开}
方法二:
 rsync -avz --exclude={1..3} /data1/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #{文件名字,这是文件名连续的文件}
方法三:
rsync -avz --exclude=1 --exclude=2 /data/ rsync_backup@192.168.1.7::king --password-file=/etc/rsync.password #多个--exclude=文件名字,虽然麻烦,不失为方法。

3)无差别同步:--delete参数

  通常是有须要在俩台服务器之间,必需要求数据同步,且实时性又不是很高的状况下,如:俩台负载均衡下面的web服务器之间的同步,或者高可用双机配置之间的同步等,rsync无差别同步很危险切记。

 6.inotify介绍

Inotify 是一种强大的、细粒度的、异步的文件系统事件监控机制,linux内核从2.6.13起,加入了Inotify支持,经过Inotify能够监控文件系统中添加、删除,修改、移动等各类细微事件,利用这个内核接口,第三方软件就能够监控文件系统下文件的各类变化状况,而inotify-tools就是这样的一个第三方软件。

inotify是rsync客户端安装和执行的

1 )查看当前系统是否支持inotify

[root@rsyncclient ~]# ll /proc/sys/fs/inotify/ 总用量 0
-rw-r--r-- 1 root root 0 9月  21 14:56 max_queued_events -rw-r--r-- 1 root root 0 9月  21 14:56 max_user_instances -rw-r--r-- 1 root root 0 9月  21 14:56 max_user_watches #显示这三个文件则证实支持。

 /proc/sys/fs/inotify/max_queued_evnets      

表示调用inotify_init时分配给inotify instance中可排队的event的数目的最大值,超出这个值的事件被丢弃,但会触发IN_Q_OVERFLOW事件。

 /proc/sys/fs/inotify/max_user_instances 

表示每个real user ID可建立的inotify instatnces的数量上限。

 /proc/sys/fs/inotify/max_user_watches 

表示每一个inotify instatnces可监控的最大目录数量。若是监控的文件数目巨大,须要根据状况,适当增长此值的大小。

2) 下载inotify源码包并编译安装

cd /home/king/tools          #安装要规范,要有本身的文件包 wget http://github.com/downloads/rvoicilas/inotifytools/inotify-tools-3.14.tar.gz #安装inotify软件包
 ll inotify-tools-3.14.tar.gz    #看一下,是否下载成功,安装包是644的权限 tar zxf inotify-tools-3.14.tar.gz  # 解压

3)inotifywait命令经常使用参数详解

[root@inotifyclient inotify-tools-3.14]# cd /usr/local/inotify-3.14/ [root@inotifyclient inotify-3.14]# ./bin/inotifywait --help -r|--recursive Watch directories recursively. #递归查询目录 -q|--quiet Print less (only print events). #打印监控事件的信息 -m|--monitor   Keep listening for events forever.  Without this option, inotifywait will exit after one  event is received. #始终保持事件监听状态 --excludei <pattern>  Like --exclude but case insensitive. #排除文件或目录时,不区分大小写。 --timefmt <fmt> strftime-compatible format string for use with %T in --format string. #指定时间输出的格式 --format <fmt>  Print using a specified printf-like format string; read the man page for more details. #打印使用指定的输出相似格式字符串 -e|--event <event1> [ -e|--event <event2> ... ] Listen for specific event(s).  If omitted, all events are  listened for. 
#经过此参数能够指定须要监控的事件,以下所示: Events: access file or directory contents were read #文件或目录被读取。 modify file or directory contents were written #文件或目录内容被修改。 attrib file or directory attributes changed #文件或目录属性被改变。 close file or directory closed, regardless of read
/write mode #文件或目录封闭,不管读/写模式。 open file or directory opened #文件或目录被打开。 moved_to file or directory moved to watched directory #文件或目录被移动至另一个目录。 move file or directory moved to or from watched directory #文件或目录被移动另外一个目录或从另外一个目录移动至当前目录。 create file or directory created within watched directory #文件或目录被建立在当前目录 delete file or directory deleted within watched directory #文件或目录被删除 unmount file system containing file or directory unmounted #文件系统被卸载

4 )编写监控脚本并加载到后台执行

mkdir -p /etc/servers/scripts      #咱们要建立这个存放脚本的目录,为了规范 cd /etc/servers/scripts           vim inotify.sh               #编辑这个脚本

脚本内容以下

#!/bin/shpath=/usr/local/inotify/bin/inotifywait
$path -mrq --format '%w%f' -e create,close_write,delete /backup|\
while read line
do
  [! -e "$line"]&& continue
  
rsync -avz --delete $line rsync_backup@192.168.1.7::king /data/ --password-file=/etc/rsync.password
done
sh inotify.sh &  #将脚本加入后台执行

 说明:\是换行的意思,continue是跳过下面的命令,相似于Java中的\t \n,continue,continue 跳出当前循环,不执行continue后续循环体内的代码,从新执行下次循环体,break 跳出循环体,直接结束循环,执行循环后的代码 好比:

pulic void TestBreak(){   for(int i=0; i < 10; i++){     if (i == 5) {       break;     } else {       System.out.print(i);     }   }   System.out.print("end"); } 输出结果:01234end pulic void TestContinue(){   for(int i=0; i < 10; i++){     if (i == 5) {       continue ;     } else {       System.out.print(i);     }   }   System.out.print("end"); } 输出结果:012346789end

简单说说吧,虽然我写代码不少bug,可是很开心呀

相关文章
相关标签/搜索