数据同步-rsync

什么是rsync?

rsync(remote rsync)是可以实现增量备份的远程(和本地)文件复制工具。
目的是实现本地主机和远程主机上的文件同步,也可以实现本地不同路径下的同步。
rsync配合计划任务还可以实现定期或周期同步。
同步方式有两中:本地推送文件到远程、从远程拉取文件到本地。

rsync同步过程

简单概念

就文件同步而言,涉及了源文件和目标文件的概念,还涉及了以哪边文件为同步基准。
举例:

  1. 想让目标主机上的文件和本地文件保持同步,则是以本地文件为同步基准,将本地文件作为源文件推送到目标主机上。
  2. 如果想让本地主机上的文件和目标主机上的文件保持同步,则目标主机上的文件为同步基准,实现方式是将目标主机上的文件作为源文件拉取到本地。
  3. 保持本地的两个文件相互同步,以本地某文件作为源,另一文件作为目标文件。

同步过程

rsync同步过程中由两部分模式组成:决定哪些文件需要同步的检查模式以及文件同步时的同步模式。

检查模式

  1. rsync同步过程中由两部分模式组成:决定哪些文件需要同步的检查模式以及文件同步时的同步模式,例如哪些文件是明确被排除不传输的。
  2. 默认情况下,rsync使用"quick check"算法快速检查源文件和目标文件的大小、mtime(修改时间)是否一致,如果不一致则需要传输。
  3. 也可以通过在rsync命令行中指定某些选项来改变quick check的检查模式,比如"–size-only"选项表示"quick check"将仅检查文件大小不同的文件作为待传输文件。
  4. rsync支持非常多的选项,其中检查模式的自定义性是非常有弹性的。

同步模式

  1. 同步模式是指在文件确定要被同步后,在同步过程发生之前要做哪些额外工作。
  2. 例如上文所说的是否要先删除源主机上没有但目标主机上有的文件,是否要先备份已存在的目标文件,是否要追踪链接文件等额外操作。
  3. rsync也提供非常多的选项使得同步模式变得更具弹性。
  4. rsync手动指定同步模式的选项更常见一些, 只有在有特殊需求时才指定检查模式,因为大多数检查模式选项都可能会影响rsync的性能。

rsync的优势

  1. 速度快:除首次全拷贝外,其他时候实现增量拷贝,传输速度快。
  2. 更安全:传输数据时可用ssh加密传输。
  3. 带宽占用更少:rsync可对数据进行分块压缩传输,相比其他文件传输工具占用更少带宽。
  4. 权限限制:非root用户也可安转和执行rsync命令。
  5. 支持目录层级递归拷贝,可以镜像保存整个目录树和文件系统。
  6. 支持限速。
  7. 支持断点续传。
  8. 支持128位MD4校验(3.0以后版本使用MD5加密)。
  9. 可以很容易做到保持原来文件的权限、时间、软硬链接等等。

rsync应用

安装rsync

rsync客户端和服务端安装一样,只是服务端有修改rsync的配置信息。

检查rsync是否安装

yum list installed | grep rsync

安装rsync

  • yum安装
yum install rsync -y
  • 源码安装
wget https://download.samba.org/pub/rsync/src/rsync-3.2.3.tar.gz
tar -xvf rsync-3.2.3.tar.gz -C /usr/local/
./configure
make && make install

#设置开机启动
echo "/usr/local/bin/rsync --daemon -config=/etc/rsyncd.conf" >> /etc/profile

配置rsync

  • 参考配置文件
#rsync 配置文件参考
cat > /etc/rsyncd.conf << EOF
# /etc/rsyncd: configuration file for rsync daemon mode
# See rsyncd.conf man page for more options.

# GLOBAL OPTIONS
uid = root                         
gid = root                                  
use chroot = no                             
max connections = 0                                                   
pid file = /var/run/rsyncd.pid             
#This will give you a separate log file
log file = /var/log/rsync.log               
motd file = /etc/rsyncd/rsyncd.motd    
lock file = /var/run/rsyncd.lock
secrets file = /etc/rsyncd/rsyncd.secrets        
#This will log every file transferred - up to 85,000+ per user, per sync
transfer logging = yes                    
log format = %t %a %m %f %b
timeout = 300

# MODULE OPTIONS
[appdata]                               
path = /appdata/                                                                                
auth users = root                         
comment = app data            
exclude = photos/
EOF

#rsync 远程登录账号密码设置
cat > /etc/rsyncd/rsyncd.secrets << EOF
root:1qaz2wsx
EOF
chmod 600 /etc/rsyncd/rsyncd.secrets

#rsync 客户端登录提示信息
cat > /etc/rsyncd/rsyncd.motd << EOF
================欢迎使用rsync================
EOF
  • 配置解释–符号解释
  1. 模块以 [模块名] 开始
  2. 参数配置行的格式是 name = value ,其中 value 可以有两种数据类型:
  • 字符串(可以不用引号定界字符串)
  • 布尔值(1/0 或 yes/no 或 true/false)
  1. 以 # 或 ; 开始的行为注释
  2. \ 为续行符
  • 配置解释–全局参数

在文件中 [module] 之外的所有配置行都是全局参数。当然也可以在全局参数部分定义模块参数,这时该参数的值就是所有模块的默认值。

参数说明默认值
address在独立运行时,用于指定的服务器运行的 IP 地址。由 xinetd 运行时将忽略此参数,使用命令行上的 –address 选项替代。本地所有IP
port指定 rsync 守护进程监听的端口号。 由 xinetd 运行时将忽略此参数,使用命令行上的–port 选项替代。873
motd file指定一个消息文件,当客户连接服务器时该文件的内容显示给客户。
pid filersync 的守护进程将其 PID 写入指定的文件。
log file指定 rsync 守护进程的日志文件,而不将日志发送给 syslog。
syslog facility指定 rsync 发送日志消息给 syslog 时的消息级别。daemon
socket options指定自定义 TCP 选项。
  • 配置解释–模块参数

模块参数主要用于定义 rsync 服务器哪个目录要被同步。模块声明的格式必须为 [module] 形式,这个名字就是在 rsync 客户端看到的名字,类似于 Samba 服务器提供的共享名。而服务器真正同步的数据是通过 path 来指定的。可以根据自己的需要,来指定多个模块,模块中可以定义以下参数:

  1. 基本模块参数
参数说明说明
path指定当前模块在 rsync 服务器上的同步路径,该参数是必须指定的。
comment给模块指定一个描述,该描述连同模块名在客户连接得到模块列表时显示给客户。
  1. 模块控制参数
参数说明默认值
use chroot指定当若为 true,则 rsync 在传输文件之前首先 chroot 到 path 参数所指定的目录下。这样做的原因是实现额外的安全防护,但是缺点是需要 root 权限,并且不能备份指向 path 外部的符号连接所指向的目录文件。true
uid指定该模块以指定的 UID 传输文件。nobody
gid指定该模块以指定的 GID 传输文件。nobody
max connections指定该模块的最大并发连接数量以保护服务器,超过限制的连接请求将被告知随后再试。0(没有限制)
lock file指定支持 max connections 参数的锁文件。/var/run/rsyncd.lock
list指定当客户请求列出可以使用的模块列表时,该模块是否应该被列出。如果设置该选项为 false,可以创建隐藏的模块。true
read only指定是否允许客户上传文件。若为 true 则不允许上传;若为 false 并且服务器目录也具有读写权限则允许上传。true
write only指定是否允许客户下载文件。若为 true 则不允许下载;若为 false 并且服务器目录也具有读权限则允许下载。false
ignore errors指定在 rsync 服务器上运行 delete 操作时是否忽略 I/O 错误。一般来说 rsync 在出现 I/O 错误时将将跳过 –delete 操作,以防止因为暂时的资源不足或其它 I/O 错误导致的严重问题。true
ignore nonreadable指定 rysnc 服务器完全忽略那些用户没有访问权限的文件。这对于在需要备份的目录中有些不应该被备份者获得的文件时是有意义的。false
timeout该选项可以覆盖客户指定的 IP 超时时间。从而确保 rsync 服务器不会永远等待一个崩溃的客户端。对于匿名 rsync 服务器来说,理想的数字是 600(单位为秒)。0 (未限制)
dont compress用来指定那些在传输之前不进行压缩处理的文件。该选项可以定义一些不允许客户对该模块使用的命令选项列表。必须使用选项全名,而不能是简称。当发生拒绝某个选项的情况时,服务器将报告错误信息然后退出。例如,要防止使用压缩,应该是:”dont compress = *”。*.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz
  1. 模块文件筛选参数
参数说明默认值
exclude指定多个由空格隔开的多个文件或目录(相对路径),并将其添加到 exclude 列表中。这等同于在客户端命令中使用 –exclude 来指定模式。
exclude from指定一个包含 exclude 规则定义的文件名,服务器从该文件中读取 exclude 列表定义。
include指定多个由空格隔开的多个文件或目录(相对路径),并将其添加到 include 列表中。这等同于在客户端命令中使用 –include 来指定模式 。
include from指定一个包含 include 规则定义的文件名,服务器从该文件中读取 include 列表定义。

注意:

  • 一个模块只能指定一个exclude 参数、一个include 参数。
  • 结合 include 和 exclude 可以定义复杂的exclude/include 规则 。
  • 这几个参数分别与相应的rsync 客户命令选项等价,唯一不同的是它们作用在服务器端。
  1. 模块用户认证参数
参数说明默认值
auth users指定由空格或逗号分隔的用户名列表,只有这些用户才允许连接该模块。这里的用户和系统用户没有任何关系。用户名和口令以明文方式存放在 secrets file 参数指定的文件中。(匿名方式)
secrets file指定一个 rsync 认证口令文件。只有在 auth users 被定义时,该文件才起作用。
strict modes指定是否监测口令文件的权限。若为 true 则口令文件只能被 rsync 服务器运行身份的用户访问,其他任何用户不可以访问该文件。TRUE

注意:

  • rsync 认证口令文件的权限一定是 600,否则客户端将不能连接服务器。
  • rsync 认证口令文件中每一行指定一个 用户名:口令对,格式为:username:passwd
  • 一般来说口令最好不要超过8个字符。若您只配置匿名访问的 rsync 服务器,则无需设置上述参数。
  1. 模块访问控制参数
参数说明默认值
hosts allow用一个主机列表指定哪些主机客户允许连接该模块。不匹配主机列表的主机将被拒绝。*
hosts deny用一个主机列表指定哪些主机客户不允许连接该模块。

注意:

  • 单个IP地址。例如:192.168.0.1
  • 整个网段。例如:192.168.0.0/24,192.168.0.0/255.255.255.0
  • 可解析的单个主机名。例如:centos,centos.bsmart.cn
  • 域内的所有主机。例如:*.bsmart.cn
  • *”则表示所有
  • 多个列表项要用空格间隔
  1. 模块日志参数
参数说明默认值
transfer logging使 rsync 服务器将传输操作记录到传输日志文件。false
log format指定传输日志文件的字段。“%o %h [%a] %m (%u) %f %l”

注意:
设置了”log file”参数时,在日志每行的开始会添加”%t [%p]“。
可以使用的日志格式定义符如下所示:

  • %a - 远程IP地址
  • %h - 远程主机名
  • %l - 文件长度字符数
  • %p - 该次 rsync 会话的 PID
  • %o - 操作类型:”send” 或 “recv”
  • %f - 文件名
  • %P - 模块路径
  • %m - 模块名
  • %t - 当前时间
  • %u - 认证的用户名(匿名时是 null)
  • %b - 实际传输的字节数
  • %c - 当发送文件时,记录该文件的校验码

启动rsync

rsync --daemon

应用rsync

帮助文档

rsync  version 3.1.2  protocol version 31
Copyright (C) 1996-2015 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, prealloc

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
     --info=FLAGS            fine-grained informational verbosity
     --debug=FLAGS           fine-grained debug verbosity
     --msgs2stderr           special output handling for debugging
 -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
     --munge-links           munge symlinks to make them safer (but unusable)
 -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
 -J, --omit-link-times       omit symlinks from --times
     --super                 receiver attempts super-user activities
     --fake-super            store/recover privileged attrs using xattrs
 -S, --sparse                handle sparse files efficiently
     --preallocate           allocate dest files before writing them
 -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 the transfer
     --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-missing-args   ignore missing source args without error
     --delete-missing-args   delete missing source args from destination
     --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
     --usermap=STRING        custom username mapping
     --groupmap=STRING       custom groupname mapping
     --chown=USER:GROUP      simple username/groupname mapping
     --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
 -M, --remote-option=OPTION  send OPTION to the remote side only
     --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=RATE          limit socket I/O bandwidth
     --outbuf=N|L|B          set output buffering to None, Line, or Block
     --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
     --checksum-seed=NUM     set block/file checksum seed (advanced)
 -4, --ipv4                  prefer IPv4
 -6, --ipv6                  prefer IPv6
     --version               print version number
(-h) --help                  show this help (-h is --help only if used alone)

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

参数解释

-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 压缩模式,当资料在传送到目的端进行档案压缩。
-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:删除那些目标位置有的文件而备份源没有的文件。
--delete-before: 接收者在传输之前进行删除操作
--password-file=FILE :从 指定密码文件中获取密码。
--bwlimit=KBPS:限制 I/O 带宽。
--filter “-filename”:需要过滤的文件。
--exclude=filname:需要过滤的文件。
--progress:显示备份过程。

应用举例

  • 从远端拉取
#格式: rsync 选项 用户名@地址:/原目录 /目的目录
rsync -avp -e 'ssh -p2222' root@192.169.1.200:/root/test/ /root/my_test/
  • 推送至远端
#格式: rsync 选项 原目录 用户名@地址:/目的目录
rsync -avp -e 'ssh -p2222' /root/my_test/ root@192.169.1.200:/root/test/ 
  • 注意
  1. 同步数据填写路径时,末尾添加“/”,例如:“/root/my_test/”表示该目录下所有文件;
  2. 同步数据填写路径时,原目录与目的目录的结尾建议添加“/”,保持目录结构一致;
  3. 同步数据填写路径时,只能在目的目录下同步一级不存在的目录,如果多层子目录不存在的情况下同步会报错;

资料查阅与学习参考来源

作者:木石文若
链接:https://www.jianshu.com/p/30af2a4edb52
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值