Rsync+inotify实现文件实时同步

简介:

 数据备份、文件备份是运维、DBA等岗位最熟悉不过的话题,这里不介绍数据库的备份,简单介绍一下文件同步工具,这样的工具有很多,Windows环境下有Goodsync、FreeFileSync等,Linux下rsync、unison等,常用的实时同步,是几种工具的组合,经过组合的工具达到文件实时同步的效果。

一、常用实时同步方案

1、NFS网络文件系统

    该方案是分布式架构中,解决不同节点对同一资源访问的问题,搭建NFS服务器,将其挂载在不同的节点,每个节点将公用的数据存储在NFS服务器上,实现文件的同步。

2、rsync+inotify

   该方案是实用量最大,资料最丰富的文件同步方案,rsync主要有基于系统用户和虚拟用户的两种方式,基于系统用户的方式和scp命令功能特性差不多,简单实用,可操作性强。inotify主要用来监控文件的变换,通过两者组合,编写一些简单的脚本,就可以实现文件和目录的实时同步。也是本文重点介绍的内容。

3、rsync+sersync

    sersync是基于inotify开发的工具,类似于inotify-tools工具,但是sersync可以记录下被监听目录中发生变化的(包括增加、删除、修改)具体某一个文件或者某一个目录的名字,然后使用rsync同步的时候,只同步发生变化的文件或者目录。

rsync+sersync组合的特点

 a、sersync可以记录被监听目录中发生变化的(增,删,改)具体某个文件或目录的名字;

 b、rsync在同步时,只同步发生变化的文件或目录(每次发生变化的数据相对整个同步目录数据来说很小,rsync在遍历查找对比文件时,速度很快),因此效率很高。

 rsync+sersync和rsync+inotify的选型

   1、同步的目录数据量不大时,建议使用rsync+inotify 

   2、同步的目录数据量很大时(几百G甚至1T以上)文件很多时,建议使用rsync+sersync

4、unison+inotify

Unison是一款跨平台的文件同步工具,不仅支持本地对本地同步,也支持通过SSH、RSH和Socket等网络协议进行同步。更棒的是,Unison支持双向同步操作,你既可以从A同步到B,也可以从B同步到A,这些都不需要额外的设定。

官方文档: 
http://www.seas.upenn.edu/~bcpierce/unison//download/releases/stable/unison-2.48.4-manual.html

二、基本环境

操作系统:CentOS 6.9 

rsync版本: rsync  version 3.0.6    官网:https://rsync.samba.org/ 

操作系统内核:2.6.32-696.6.3.el6.x86_64 

inotify版本:inotify-tools-3.14  下载地址如下:

1
http: //github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz

三、rsync的介绍

1、rsyn的特性

  •     可以镜像保存整个目录树和文件系统。

  •     可以很容易做到保持原来文件的权限、时间、软硬链接等等。

  •     无须特殊权限即可安装。

  •     快速:第一次同步时 rsync 会复制全部内容,但在下一次只传输修改过的文件。

  •     压缩传输:rsync 在传输数据的过程中可以实行压缩及解压缩操作,因此可以使用更少的带宽。

  •     安全:可以使用scp、ssh等方式来传输文件,当然也可以通过直接的socket连接。

  •     支持匿名传输,以方便进行网站镜象。

  •     选择性保持:符号连接,硬链接,文件属性,权限,时间等 

2、rsync与scp的区别

  •    scp无法满足大量数据备份,类似windows的复制

  •   rsync支持变复制 ,边统计,边比较

3、rsync 数据同步方式

    推push:一台主机负责吧数据传送给其他主机,服务器开销很大,比较适合后端服务器少的情况

    拉pull: 所有主机定时去找一主机拉数据,可能就会导致数据缓慢

    推:目的主机配置为rsync服务器,源主机周期性的使用rsync命令把要同步的目录推过去

    拉:源主机配置为rsync服务器,目的主机周期性的使用rsync命令把要同步的目录拉过来

    两种方案,rsync都有对应的命令来实现

4、Xinetd管理Rsync工作原理


5、rsync 命令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
rsync 命令和 scp 命令很相似
常用参数:
-a, --archive archive mode 权限保存模式,相当于 -rlptgoD 参数,存档,递归,保持属性等
-r, --recursive 复制所有下面的资料,递归处理
-p, --perms 保留档案权限 ,文件原有属性
-t, -- times  保留时间点,文件原有时间
-g, --group 保留原有属组
-o, --owner 保留档案所有者(root only)
-D, --devices 保留device资讯(root only) 
-l, --links 复制所有的连接 ,拷贝连接文件
-z, --compress 压缩模式, 当资料在传送到目的端进行档案压缩.  –azP
-H, --hard-links 保留硬链接文件
-A, --acls 保留ACL属性文件,需要配合--perms
-P,-P参数和 --partial --progress 相同.只是为了把参数简单化,表示传进度
--version, 输出 rsync 版本 
- v  , --verbose 复杂的输出信息 
-u, --update 仅仅进行更新,也就是跳过已经存在的目标位置,并且文件时间要晚于要备份的文件,不覆盖新的文件
--port=PORT, 定义rsyncd(daemon)要运行的port(预设为tcp 873) 
--delete, 删除那些目标位置有的文件而备份源没有的文件 
--password- file =FILE ,从 FILE 中得到密码 
--bwlimit=KBPS, 限制 I /O  带宽 
--filter “-filename”,需要过滤的文件 
--exclude=filname,需要过滤的文件
--progress,显示备份过程
 
帮助文档
[root@localhost  install ] # rsync   --help
rsync   version 3.0.6  protocol version 30
Copyright (C) 1996-2009 by Andrew Tridgell, Wayne Davison, and others.
Web site: http: //rsync .samba.org/
Capabilities:
     64-bit files, 64-bit inums, 64-bit timestamps, 64-bit long ints,
     socketpairs, hardlinks, symlinks, IPv6, batchfiles, inplace,
     append, ACLs, xattrs, iconv, symtimes
 
rsync  comes with ABSOLUTELY NO WARRANTY.  This is  free  software, and you
are welcome to redistribute it under certain conditions.  See the GNU
General Public Licence  for  details.
 
rsync  is a  file  transfer program capable of efficient remote update
via a fast differencing algorithm.
 
Usage:  rsync  [OPTION]... SRC [SRC]... DEST
   or    rsync  [OPTION]... SRC [SRC]... [USER@]HOST:DEST
   or    rsync  [OPTION]... SRC [SRC]... [USER@]HOST::DEST
   or    rsync  [OPTION]... SRC [SRC]...  rsync : // [USER@]HOST[:PORT] /DEST
   or    rsync  [OPTION]... [USER@]HOST:SRC [DEST]
   or    rsync  [OPTION]... [USER@]HOST::SRC [DEST]
   or    rsync  [OPTION]...  rsync : // [USER@]HOST[:PORT] /SRC  [DEST]
The  ':'  usages connect via remote shell,  while  '::'  'rsync://'  usages connect
to an  rsync  daemon, and require SRC or DEST to start with a module name.
 
Options
  - v , --verbose               increase verbosity
  -q, --quiet                 suppress non-error messages
      --no-motd               suppress daemon-mode MOTD (see manpage caveat)
  -c, --checksum              skip based on checksum, not mod- time  & size
  -a, --archive               archive mode; equals -rlptgoD (no -H,-A,-X)
      --no-OPTION             turn off an implied OPTION (e.g. --no-D)
  -r, --recursive             recurse into directories
  -R, --relative              use relative path names
      --no-implied- dirs        don't send implied  dirs  with --relative
  -b, --backup                 make  backups (see --suffix & --backup- dir )
      --backup- dir =DIR         make  backups into hierarchy based  in  DIR
      --suffix=SUFFIX          set  backup suffix (default ~ w /o  --backup- dir )
  -u, --update                skip files that are newer on the receiver
      --inplace               update destination files  in -place (SEE MAN PAGE)
      --append                append data onto shorter files
      --append-verify         like --append, but with old data  in  file  checksum
  -d, -- dirs                   transfer directories without recursing
  -l, --links                 copy symlinks as symlinks
  -L, --copy-links            transform  symlink  into referent  file /dir
      --copy-unsafe-links     only  "unsafe"  symlinks are transformed
      --safe-links            ignore symlinks that point outside the  source  tree
  -k, --copy-dirlinks         transform  symlink  to a  dir  into referent  dir
  -K, --keep-dirlinks         treat symlinked  dir  on receiver as  dir
  -H, --hard-links            preserve hard links
  -p, --perms                 preserve permissions
  -E, --executability         preserve the  file 's executability
      -- chmod =CHMOD           affect  file  and /or  directory permissions
  -A, --acls                  preserve ACLs (implies --perms)
  -X, --xattrs                preserve extended attributes
  -o, --owner                 preserve owner (super-user only)
  -g, --group                 preserve group
      --devices               preserve device files (super-user only)
      --copy-devices          copy device contents as regular  file
      --specials              preserve special files
  -D                          same as --devices --specials
  -t, -- times                  preserve modification  times
  -O, --omit- dir - times         omit directories from -- times
      --super                 receiver attempts super-user activities
      --fake-super            store /recover  privileged attrs using xattrs
  -S, --sparse                handle sparse files efficiently
  -n, --dry-run               perform a trial run with no changes made
  -W, --whole- file             copy files whole (without delta-xfer algorithm)
  -x, --one- file -system       don't cross filesystem boundaries
  -B, --block-size=SIZE       force a fixed checksum block-size
  -e, --rsh=COMMAND           specify the remote shell to use
      -- rsync -path=PROGRAM    specify the  rsync  to run on the remote machine
      --existing              skip creating new files on receiver
      --ignore-existing       skip updating files that already exist on receiver
      --remove- source -files   sender removes synchronized files (non- dirs )
      --del                   an  alias  for  --delete-during
      --delete                delete extraneous files from destination  dirs
      --delete-before         receiver deletes before transfer, not during
      --delete-during         receiver deletes during transfer (default)
      --delete-delay           find  deletions during, delete after
      --delete-after          receiver deletes after transfer, not during
      --delete-excluded       also delete excluded files from destination  dirs
      --ignore-errors         delete even  if  there are I /O  errors
      --force                 force deletion of directories even  if  not empty
      --max-delete=NUM        don't delete  more  than NUM files
      --max-size=SIZE         don't transfer any  file  larger than SIZE
      --min-size=SIZE         don't transfer any  file  smaller than SIZE
      --partial               keep partially transferred files
      --partial- dir =DIR       put a partially transferred  file  into DIR
      --delay-updates         put all updated files into place at transfer's end
  -m, --prune-empty- dirs       prune empty directory chains from the  file -list
      --numeric-ids           don't map uid /gid  values by user /group  name
      --timeout=SECONDS        set  I /O  timeout  in  seconds
      --contimeout=SECONDS     set  daemon connection timeout  in  seconds
  -I, --ignore- times           don't skip files that match  in  size and mod- time
      --size-only             skip files that match  in  size
      --modify-window=NUM     compare mod- times  with reduced accuracy
  -T, --temp- dir =DIR          create temporary files  in  directory DIR
  -y, --fuzzy                  find  similar  file  for  basis  if  no dest  file
      --compare-dest=DIR      also compare destination files relative to DIR
      --copy-dest=DIR         ... and include copies of unchanged files
      --link-dest=DIR         hardlink to files  in  DIR when unchanged
  -z, --compress              compress  file  data during the transfer
      --compress-level=NUM    explicitly  set  compression level
      --skip-compress=LIST    skip compressing files with a suffix  in  LIST
  -C, --cvs-exclude           auto-ignore files the same way CVS does
  -f, --filter=RULE           add a  file -filtering RULE
  -F                          same as --filter= 'dir-merge /.rsync-filter'
                              repeated: --filter= '- .rsync-filter'
      --exclude=PATTERN       exclude files matching PATTERN
      --exclude-from=FILE      read  exclude patterns from FILE
      --include=PATTERN       don't exclude files matching PATTERN
      --include-from=FILE      read  include patterns from FILE
      --files-from=FILE        read  list of  source - file  names from FILE
  -0, --from0                 all *-from /filter  files are delimited by 0s
  -s, --protect-args          no space-splitting; only wildcard special-chars
      --address=ADDRESS       bind address  for  outgoing socket to daemon
      --port=PORT             specify double-colon alternate port number
      --sockopts=OPTIONS      specify custom TCP options
      --blocking-io           use blocking I /O  for  the remote shell
      --stats                 give some  file -transfer stats
  -8, --8-bit-output          leave high-bit chars unescaped  in  output
  -h, --human-readable        output numbers  in  a human-readable  format
      --progress              show progress during transfer
  -P                          same as --partial --progress
  -i, --itemize-changes       output a change-summary  for  all updates
      --out- format =FORMAT     output updates using the specified FORMAT
      --log- file =FILE         log what we're doing to the specified FILE
      --log- file - format =FMT   log updates using the specified FMT
      --password- file =FILE     read  daemon-access password from FILE
      --list-only             list the files instead of copying them
      --bwlimit=KBPS          limit I /O  bandwidth; KBytes per second
      --write-batch=FILE      write a batched update to FILE
      --only-write-batch=FILE like --write-batch but w /o  updating destination
      -- read -batch=FILE        read  a batched update from FILE
      --protocol=NUM          force an older protocol version to be used
      --iconv=CONVERT_SPEC    request charset conversion of filenames
  -4, --ipv4                  prefer IPv4
  -6, --ipv6                  prefer IPv6
      --version               print version number
(-h) --help                  show this help (-h works with no other options)
 
Use  "rsync --daemon --help"  to see the daemon-mode  command -line options.
Please see the  rsync (1) and rsyncd.conf(5)  man  pages  for  full documentation.
See http: //rsync .samba.org/  for  updates, bug reports, and answers

四、服务安装与配置

1、安装rsync   

1
yum   install   -y  rsync

2、基于系统用户的备份

   基于系统用户的备份,不需要配置rsyncd服务,这时的rsync和scp非常的类似,测试规划如下:

主机序号 主机IP 备份目录 安装软件 同步方式
1 192.168.223.128(数据源服务器) /data/ rsync 主动方式
2 192.168.223.129(备份存储服务器) /databack/rsyncback

测试:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
主机:192.168.223.128    推送模式
[root@data128 ~] # cd  /data
[root@data128 data] # l 
- bash : l:  command  not found
[root@data128 data] # ls 
winner.txt
[root@data128 data] # ls 
winner.txt
[root@data128 data] # rsy
rsync      rsyslogd  
[root@data128 data] # rsync   -azP    /data/   root@192.168.223.129:/databack/rsyncback
sending incremental  file  list
./
. pwd .lock
            0 100%    0.00kB /s     0:00:00 (xfer #1, to-check=1/3)
winner.txt
         4588 100%    0.00kB /s     0:00:00 (xfer #2, to-check=0/3)
 
sent 659 bytes  received 53 bytes  284.80 bytes /sec
total size is 4588  speedup is 6.44
[root@data128 data]
主机:192.168.223.129 主机测试
 
[root@databack129 ~] # cd   /databack/rsyncback/
[root@databack129 rsyncback] # ls 
winner.txt
[root@databack129 rsyncback]
 
主动获取模式测试:
在192.168.223.128 主机上创建新文件  
[root@data128 data] # touch {1,3,5,7,9,10}.txt
[root@data128 data] # ls 
10.txt  1.txt  3.txt  5.txt  7.txt  9.txt  winner.txt
[root@data128 data]
主机:192.168.223.129   获取数据
[root@databack129 rsyncback] # rsync   -azP   root@192.168.223.128:/data/  ./
receiving incremental  file  list
./
1.txt
            0 100%    0.00kB /s     0:00:00 (xfer #1, to-check=6/9)
10.txt
            0 100%    0.00kB /s     0:00:00 (xfer #2, to-check=5/9)
3.txt
            0 100%    0.00kB /s     0:00:00 (xfer #3, to-check=4/9)
5.txt
            0 100%    0.00kB /s     0:00:00 (xfer #4, to-check=3/9)
7.txt
            0 100%    0.00kB /s     0:00:00 (xfer #5, to-check=2/9)
9.txt
            0 100%    0.00kB /s     0:00:00 (xfer #6, to-check=1/9)
 
sent 128 bytes  received 368 bytes  330.67 bytes /sec
total size is 4588  speedup is 9.25

从命令的执行过程中可以看出这个命令和scp非常相似,在拷贝过程中没有输入密码是因为两个主机之间做了免密码登录,而数据传输过程中也是使用了SSH传输协议。关于SSH免密码登录请自行搜索资料。

2.1 基于系统用户的备份脚本

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#!/bin/bash
rsync  -az --delete root@192.168.223.128: /data/    /databack/rsyncback/
tar  czvf  rsync -` date  +%Y-%m-%d`. tar .gz   /databack/rsyncback/ *  
 
执行情况:
[root@databack129 server] #   sh  -x  rsync.sh 
rsync  -az --delete root@192.168.223.128: /data/  /databack/rsyncback/
++  date  +%Y-%m-%d
tar  czvf  rsync -2017-09-16. tar .gz  /databack/rsyncback/10 .txt  /databack/rsyncback/1 .txt  /databack/rsyncback/3 .txt  /databack/rsyncback/5 .txt  /databack/rsyncback/7 .txt  /databack/rsyncback/9 .txt  /databack/rsyncback/winner .txt
tar : 从成员名中删除开头的“/”
/databack/rsyncback/10 .txt
/databack/rsyncback/1 .txt
/databack/rsyncback/3 .txt
/databack/rsyncback/5 .txt
/databack/rsyncback/7 .txt
/databack/rsyncback/9 .txt
/databack/rsyncback/winner .txt
[root@databack129 server]
 
[root@databack129 server] # tar   xzvf  rsync-2017-09-16.tar.gz 
databack /rsyncback/10 .txt
databack /rsyncback/1 .txt
databack /rsyncback/3 .txt
databack /rsyncback/5 .txt
databack /rsyncback/7 .txt
databack /rsyncback/9 .txt
databack /rsyncback/winner .txt
[root@databack129 server] # ls 
databack   rsync -2017-09-16. tar .gz   rsync .sh  xtrabackupmysql.sh
[root@databack129 server] # cd  databack/rsyncback/
[root@databack129 rsyncback] # ls 
10.txt  1.txt  3.txt  5.txt  7.txt  9.txt  winner.txt
[root@databack129 rsyncback] #

2.2 基于系统用户的实时备份

   在实时备份中,我们会选用inotif做文件的监控,安装方式为源码包,需要gcc等安装环境,文件下载等根据上面的地址下载就可以,可以使用wget加地址下载,下面对下载和安装做相关的演示。

数据实时同步规划(rsync+系统用户)
主机序号 主机IP 备份目录 安装软件 同步方式
1 192.168.223.128(数据源服务器) /data/ rsync+inotify 主动方式
2 192.168.223.129(备份存储服务器) /databack/rsyncback
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
[root@databack129  install ] # wget   http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz
--2017-09-16 23:35:15--  http: //github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz
正在解析主机 github.com... 192.30.255.112, 192.30.255.113
正在连接 github.com|192.30.255.112|:80... 已连接。
已发出 HTTP 请求,正在等待回应... 302 Found
位置:http: //101 .96.10.63 /github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz [跟随至新的 URL]
--2017-09-16 23:35:15--  http: //101 .96.10.63 /github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz
正在连接 101.96.10.63:80... 已连接。
已发出 HTTP 请求,正在等待回应... 301 Moved Permanently
位置:https: //github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz [跟随至新的 URL]
--2017-09-16 23:35:16--  https: //github .com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz
正在连接 github.com|192.30.255.112|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 302 Found
位置:https: //cloud .github.com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz [跟随至新的 URL]
--2017-09-16 23:35:18--  https: //cloud .github.com /downloads/rvoicilas/inotify-tools/inotify-tools-3 .14. tar .gz
正在解析主机 cloud.github.com... 54.192.75.93, 54.192.75.223, 54.192.75.185, ...
正在连接 cloud.github.com|54.192.75.93|:443... 已连接。
已发出 HTTP 请求,正在等待回应... 200 OK
长度:358772 (350K) [null]
正在保存至: “inotify-tools-3.14. tar .gz”
 
31% [===============>                                    ] 113,669     36.5K /s  eta(英国中部时36% [=================>                                  ] 130,053     35.6K /s  eta(英国中部时45% [======================>                             ] 162,821     38.5K /s  eta(英国中部时54% [===========================>                        ] 195,589     40.9K /s  eta(英国中部时58% [=============================>                      ] 211,517     41.3K /s  eta(英国中部时63% [================================>                   ] 227,901     33.1K /s  eta(英国中部时68% [==================================>                 ] 244,285     28.3K /s  eta(英国中部时72% [====================================>               ] 260,669     28.1K /s  eta(英国中部时77% [=======================================>            ] 277,509     25.6K /s  eta(英国中部时81% [=========================================>          ] 293,893     20.5K /s  eta(英国中部时86% [===========================================>        ] 310,277     20.7K /s  eta(英国中部时91% [==============================================>     ] 326,661     18.2K /s  eta(英国中部时95% [================================================>   ] 343,045     17.9K /s  eta(英国中部时100%[===================================================>] 358,772     17.6K /s  eta(英国中部时100%[===================================================>] 358,772     17.6K /s    in  20s     
 
2017-09-16 23:35:40 (17.6 KB /s ) - 已保存 “inotify-tools-3.14. tar .gz” [358772 /358772 ])
编译安装
[root@databack129 inotify-tools-3.14] # ./configure &&make  &&make install
checking  for  a BSD-compatible  install ...  /usr/bin/install  -c
checking whether build environment is sane...  yes
checking  for  a thread-safe  mkdir  -p...  /bin/mkdir  -p
checking  for  gawk ...  gawk
checking whether  make  sets $(MAKE)...  yes
checking whether  make  sets $(MAKE)... (cached)  yes
checking  for  gcc... gcc
checking  for  C compiler default output  file  name... a.out
checking whether the C compiler works...  yes
checking whether we are cross compiling... no
checking  for  suffix of executables... 
checking  for  suffix of object files... o
checking whether we are using the GNU C compiler...  yes
checking whether gcc accepts -g...  yes
checking  for  gcc option to accept ISO C89... none needed
checking  for  style of include used by
......
test  -z  "/usr/local/share/man/man1"  ||  /bin/mkdir  -p  "/usr/local/share/man/man1"
  /usr/bin/install  -c -m 644 inotifywait.1 inotifywatch.1  '/usr/local/share/man/man1'
make [2]: Leaving directory ` /usr/install/inotify-tools-3 .14 /man '
make [1]: Leaving directory ` /usr/install/inotify-tools-3 .14 /man '
make [1]: Entering directory ` /usr/install/inotify-tools-3 .14'
make [2]: Entering directory ` /usr/install/inotify-tools-3 .14'
make [2]: Nothing to be  done  for  ` install - exec -am'.
make [2]: Nothing to be  done  for  ` install -data-am'.
make [2]: Leaving directory ` /usr/install/inotify-tools-3 .14'
make [1]: Leaving directory ` /usr/install/inotify-tools-3 .14'
 
 
安装成功
将  /usr/local/bin/inotifywait 等 相关命令加入系统环境变量或者通过软链接到 /usr/bin/
[root@databack129 inotify-tools-3.14] # ln -s /usr/local/bin/*  /usr/bin/
[root@databack129 inotify-tools-3.14] # inotifywait   OK成功

 实时监控备份脚本

1
2
3
4
5
6
7
8
#/bin/bash
LocalPath= /data/ 
RemotrHost=root@192.168.223.129: /databin/
 
inotifywait -mrq -e modify,delete,create,attrib ${LocalPath} |  while  read  D E F
         do
                 /usr/bin/rsync  -ahqzt --delete ${LocalPath}  $RemotrHost
         done

测试结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
[root@data128 server] # sh  rsync.sh 
另开一个终端 
[root@data128 data] # ls 
10.txt  1.txt  3.txt  5.txt  7.txt  9.txt  winner.txt
[root@data128 data] # touch  {11,12,13,15}.txt
[root@data128 data] # echo  "rsync+inotify-tool"> {1,3,5}.txt
- bash : {1,3,5}.txt: ambiguous redirect
[root@data128 data] # echo  "rsync+inotify-tool"> 1.txt
[root@data128 data] # echo  "rsync+inotify-tool"> 2.txt
[root@data128 data]
 
129主机检查同步情况
[root@databack129 inotify-tools-3.14] # cd   /datab
databack/ databin/  
[root@databack129 inotify-tools-3.14] # cd   /databack/rsyncback/
[root@databack129 rsyncback] # ls 
10.txt  11.txt  12.txt  13.txt  15.txt  1.txt  3.txt  5.txt  7.txt  9.txt  winner.txt
[root@databack129 rsyncback] # cat  1.txt 
rsync +inotify-tool
[root@databack129 rsyncback] # cat  3.txt 
[root@databack129 rsyncback] # cat  5.txt 
[root@databack129 rsyncback] # cat  2.txt 
rsync +inotify-tool
[root@databack129 rsyncback] #

  经过验证基于系统的文件实时同步是不存在任何问题的,实现了我们初级的需求与规划,接下可以配置基于rsync用户的文件实时同步服务。

3、基于rsyncd服务的文件实时同步

数据实时同步规划(rsync+rsync用户)
主机序号 主机IP 备份目录 安装软件 同步方式
1 192.168.223.128(数据源服务器) /data/ rsync+inotify 推送
2 192.168.223.129(备份存储服务器) /databack/rsyncback rsyncd

192.168.223.128主机需要安装rsync+inotify,我们在测试上面的服务时已经安装,所以不需要再安装,更改相关的配置即可。192.168.223.129需要安装和配置rsyncd,而rsync服务是由xinetd服务管理,所以我们需要安装xinetd服务。

1
2
3
4
5
6
7
8
9
10
11
yum   install    xinetd
 
[root@data128] # yum  install   xinetd  -y
已加载插件:fastestmirror
设置安装进程
Loading mirror speeds from cached hostfile
  * base: mirrors.163.com
  * extras: mirror.lzu.edu.cn
  * updates: centos.ustc.edu.cn
包 2:xinetd-2.3.14-40.el6.x86_64 已安装并且是最新版本
无须任何处理

启动rsync服务需要更改相关配置 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
[root@databack129 rsyncback] # vi /etc/xinetd.d/rsync
# default: off
# description: The rsync server is a good addition to an ftp server, as it \
#       allows crc checksumming etc.
service  rsync
{
         disable = no            #将这里的yes更改为no
         flags           = IPv6
         socket_type     = stream
         wait            = no
         user            = root
         server          =  /usr/bin/rsync
         server_args     = --daemon
         log_on_failure  += USERID
}
 
启动服务
[root@databack129 rsyncback] # /etc/init.d/xinetd restart
停止 xinetd:                                              [失败]
正在启动 xinetd:                                          [确定]
或者以下方式
[root@databack129 rsyncback] # rsync --daemon --config=/etc/rsyncd.conf
Failed to parse config  file /etc/rsyncd .conf
 
默认情况下 /etc/rsyncd .conf该文件不存在需要我们手动去创建

创建rsyncd.conf文件 以及其相关介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
uid =nobody                               #运行进程的身份
gid =nobody                               #运行进程的组
address =192.168.223.129                           #监听IP
port =873                            #监听端口
hosts allow =192.168.223.128                     #允许同步客户端的IP地址,可以是网段,或者用*表示所有 192.168.1.0/24或192.168.1.0/255.255.255.0
use chroot = yes                                 #是否囚牢,锁定家目录,rsync被黑之后,黑客无法再rsync运行的家目录之外创建文件,选项设置为yes
max connections =5                              #最大连接数
pid  file  = /var/run/rsyncd .pid           #进程PID,自动生成
lock  file  = /var/run/rsync .lock              #指max connectios参数的锁文件
log  file  = /var/log/rsyncd .log           #日志文件位置
motd  file  = /etc/rsyncd .motd           #客户端登陆之后弹出的消息,需要创建
  
[databack]                  #共享模块名称
path = /databack/rsyncback          #路径
comment =used  for  web-data root     #描述
readonly  yes                     #只读方式(只可以下载)
list = yes                        #是否允许查看模块信息
auth  users  = rsyncuser                 #备份的用户,和系统用户无关
secrets  file  = /etc/rsync . passwd      #存放用户的密码文件,格式是  用户名:密码
创建提示文件和用户密码
[root@databack129 rsyncback] # vi   /etc/rsync.passwd
rsyncuser:password123
[root@databack129 rsyncback] # cat  /etc/rsync.passwd
rsyncuser:password123
[root@databack129 rsyncback] # chmod 600 /etc/rsync.passwd #目录权限必须是700或者600,否则的话身份验证会失效,设置rsync user的时候
[root@databack129 rsyncback] #
启动服务测试:
[root@databack129 rsyncback] # rsync --daemon --config=/etc/rsyncd.conf
或者
[root@databack129 rsyncback] # /etc/init.d/xinetd restart
 
[root@databack129 rsyncback] # rsync --daemon --config=/etc/rsyncd.conf
[root@databack129 rsyncback] # netstat -antup | grep :873
tcp        0      0 192.168.223.129:873         0.0.0.0:*                   LISTEN      7299 /rsync

测试文件同步服务(192.168.223.128上面推送)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
[root@data128 data] # rsync  -azp /data/  rsyncuser@192.168.223.129::databack
Welcome to Backup Server
 
Password:                      #输入密码password123
 
[root@data128 data] # ls 
10.txt          DIR_COLORS               init.conf       mtab            securetty
11.txt          DIR_COLORS.256color      inittab         my.cnf          services
12.txt          DIR_COLORS.lightbgcolor  inputrc         my.cnf.rpmnew   sestatus.conf
13.txt          dracut.conf              issue           networks        shadow
15.txt          environment              issue.net       nsswitch.conf   shadow-
1.txt           ethers                   kdump.conf       passwd           shells
2.txt           exports                  krb5.conf        passwd -         statetab
3.txt           favicon.png              ld.so.cache      printcap         sudo .conf
5.txt           filesystems              ld.so.conf      profile         sudoers
7.txt           fstab                    libaudit.conf   protocols        sudo -ldap.conf
9.txt           gai.conf                 libuser.conf    rc              sysctl.conf
adjtime         group                    localtime       rc. local         system-release
aliases         group-                   login.defs      rc.sysinit      system-release-cpe
aliases.db      grub.conf                logrotate.conf  redhat-release  virc
asound.conf     gshadow                  magic           resolv.conf     wgetrc
bashrc          gshadow-                 mailcap         rpc             winner.txt
centos-release  host.conf                 man .config      rsyncd.conf     xinetd.conf
crypttab        hosts                    mime.types      rsyncd.secrets  yum.conf
csh.cshrc       hosts.allow              mke2fs.conf     rsyslog.conf
csh.login       hosts.deny               motd            rwtab
 
 
192.168.223.129主机上检查推送结果
[root@databack129 rsyncback] # ls 
10.txt          DIR_COLORS               init.conf       mtab            securetty
11.txt          DIR_COLORS.256color      inittab         my.cnf          services
12.txt          DIR_COLORS.lightbgcolor  inputrc         my.cnf.rpmnew   sestatus.conf
13.txt          dracut.conf              issue           networks        shadow
15.txt          environment              issue.net       nsswitch.conf   shadow-
1.txt           ethers                   kdump.conf       passwd           shells
2.txt           exports                  krb5.conf        passwd -         statetab
3.txt           favicon.png              ld.so.cache      printcap         sudo .conf
5.txt           filesystems              ld.so.conf      profile         sudoers
7.txt           fstab                    libaudit.conf   protocols        sudo -ldap.conf
9.txt           gai.conf                 libuser.conf    rc              sysctl.conf
adjtime         group                    localtime       rc. local         system-release
aliases         group-                   login.defs      rc.sysinit      system-release-cpe
aliases.db      grub.conf                logrotate.conf  redhat-release  virc
asound.conf     gshadow                  magic           resolv.conf     wgetrc
bashrc          gshadow-                 mailcap         rpc             winner.txt
centos-release  host.conf                 man .config      rsyncd.conf     xinetd.conf
crypttab        hosts                    mime.types      rsyncd.secrets  yum.conf
csh.cshrc       hosts.allow              mke2fs.conf     rsyslog.conf
csh.login       hosts.deny               motd            rwtab
 
删除192.168.223.128下 /data 数据

实时同步测试

客户端创建密码文件 (192.168.223.128)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
[root@data128 data] # vi /etc/rsync_client.pwd
password123
更改权限
[root@data128 data] # chmod 600 /etc/rsync_client.pwd
 
执行以下命令
 
[root@data128 data] # rsync  -azP  --delete  --password-file=/etc/rsync_client.pwd  /data/  rsyncuser@192.168.223.129::databack
这时候客户端就不需要输入密码了
编写实时监控同步脚本
 
#/bin/bash
LocalPath= /data/ 
RemotrHost=root@192.168.223.129: /databack/rsyncback/
  #inotifywait   -mrq -e create,move,delete,modify  /data/bin* 
 
inotifywait -mrq -e modify,delete,create,attrib ${LocalPath} |  while  read  D E F
         do
              
  rsync   -azP  --delete  --password- file = /etc/rsync_client . pwd   /data/   rsyncuser@192.168.223.129::databack
 
 
  done
 
  
  执行脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[root@data128 server] # sh  -x   rsyncinotify.sh  
另一个中端执行 cp   /etc/ *   /data/   
total size is 838095  speedup is 591.88
read  D E F
rsync  -azP --delete --password- file = /etc/rsync_client . pwd  /data/  rsyncuser@192.168.223.129::databack
Welcome to Backup Server
sending incremental  file  list
sent 1408 bytes  received 8 bytes  944.00 bytes /sec
total size is 838095  speedup is 591.88
read  D E F
rsync  -azP --delete --password- file = /etc/rsync_client . pwd  /data/  rsyncuser@192.168.223.129::databack
Welcome to Backup Server
sending incremental  file  list
sent 1408 bytes  received 8 bytes  2832.00 bytes /sec
total size is 838095  speedup is 591.88
read  D E F
rsync  -azP --delete --password- file = /etc/rsync_client . pwd  /data/  rsyncuser@192.168.223.129::databack

192.168.223.129 主机的数据情况

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
[root@databack129 rsyncback] # ls 
adjtime                  init.conf       protocols
aliases                  inittab         rc
aliases.db               inputrc         rc. local
asound.conf              issue           rc.sysinit
bashrc                   issue.net       redhat-release
centos-release           kdump.conf      resolv.conf
crypttab                 krb5.conf       rpc
csh.cshrc                ld.so.cache     rsync_client. pwd
csh.login                ld.so.conf      rsyncd.conf
DIR_COLORS               libaudit.conf   rsyncd.secrets
DIR_COLORS.256color      libuser.conf    rsyslog.conf
DIR_COLORS.lightbgcolor  localtime       rwtab
dracut.conf              login.defs      securetty
environment              logrotate.conf  services
ethers                   magic           sestatus.conf
exports                  mailcap         shadow
favicon.png               man .config      shadow-
filesystems              mime.types      shells
fstab                    mke2fs.conf     statetab
gai.conf                 motd             sudo .conf
group                    mtab            sudoers
group-                   my.cnf           sudo -ldap.conf
grub.conf                my.cnf.rpmnew   sysctl.conf
gshadow                  networks        system-release
gshadow-                 nsswitch.conf   system-release-cpe
host.conf                 passwd           virc
hosts                     passwd -         wgetrc
hosts.allow               printcap         xinetd.conf
hosts.deny               profile         yum.conf
[root@databack129 rsyncback] # ls  |wc
      87      87     888
      
  删除同步:
  [root@data128 data] # rm  -f  ./*
[root@data128 data]
 
[root@databack129 rsyncback] # ls   #结果为空
[root@databack129 rsyncback] #

  到这里基础的数据同步基本上做完,但是忽略部分数据以及脚本日志信息还需要继续完善,后期持续完善!




本文转自 tianya1993 51CTO博客,原文链接:http://blog.51cto.com/dreamlinux/1965970,如需转载请自行联系原作者

相关文章
|
3月前
|
监控 安全 Unix
Rsync+Inotify实现数据实时同步
Rsync+Inotify实现数据实时同步
|
监控
inotify+rsync实现实时同步数据
inotify+rsync实现实时同步数据
100 0
|
10月前
|
监控 Linux
rsync+inotify实时同步
rsync+inotify实时同步
|
监控 安全 Shell
使用 inotify 和 rsync 实现文件实时同步
使用 inotify 和 rsync 实现文件实时同步
288 1
|
监控 Linux
配置inotify + rsync 实现实时同步
配置inotify + rsync 实现实时同步
241 0
配置inotify + rsync 实现实时同步
|
监控 安全 Shell
inotify+rsync实现实时同步
1.1 什么是实时同步:如何实现实时同步 要利用监控服务(inotify),监控同步数据服务器目录中信息的变化 发现目录中数据产生变化,就利用rsync服务推送到备份服务器上 1.2 实现实时同步的方法    inotify+rsync 方式实现数据同步    sersync 方式实现实时数据同步 详情参照:http://www.cnblogs.com/clsn/p/7707828.html 1.2.1 实时同步原理介绍   1.3 inotify+rsync 方式实现数据同步 1.3.1 Inotify简介   Inotify是一种强大的,细粒度的。
1839 0
|
数据安全/隐私保护 网络安全 Shell
|
Web App开发 监控 网络协议