码迷,mamicode.com
首页 > 系统相关 > 详细

Linux下如何使用Rsync备份服务器重要数据

时间:2021-07-19 16:53:23      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:错误   led   remote   思路   oca   备份文件   选项   介绍   rbo   

 

            技术图片

Rsync介绍:

  • Rsync英文全称Remote synchronization,从软件的名称就可以看出来,Rsync具有可使本地和远程两台主机之间的数据快速复制同步镜像,远程备份的功能,这个功能类似ssh带的scp命令,但又优于scp命令的功能,scp每次都是全量拷贝,而rsync可以增量拷贝。
  • Rsync还可以在本地主机的不同分区或目录之间全量及增量的复制数据,这又类似cp命令,但同样也优于cp命令,cp每次都是全量拷贝,而rsync可以增量拷贝。
  • Rsync是一款开源的,快速的,多功能的,可实现全量及增量的本地或远程数据同步备份的优秀工具。Rsync软件适用于unix/linux/windows等多种操作系统平台。

Rsync优点:

  • 支持增量备份,第一次全量备份,第二次增量备份。边复制边比较边统计,传输效率高。
  • 数据集中备份,客户端可以推送数据至服务端,也可以从服务端获取数据,与客户端为参照物。
  • 保持文件属性,符号链接,硬链接,权限,时间等。
  • 安全方式传输,Rsync本身不对数据加密,使用ssh作为传输端口。
  • 指定排除文件,排除无需同步的文件或目录。
  • 进程方式同步,rsync运行在C/S架构,通过进程方式传输文件或数据,默认监听tcp873端口。

Rsync缺点:

  • 1.大量小文件同步会比较慢,需要比对时间较长,可能造成Rsync进程停止。

   解决思路:将小文件进行打包,然后再同步,减小比对时间,传输效率更高

  • 2.同步大文件会出现中断情况,而且长时间同步会造成网络资源耗尽。

   解决思路:配置限速同步,未同步完之前修改为隐藏文件,同步完后修改为正常文件

 Rsync语法格式:

SYNOPSIS
       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
    
测试发送:rsync -nr -i SRC  DEST
OPTION
  -a, --archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD
  -v, --verbose 详细模式输出
  -p, --perms 保持文件权限
  -g, --group 保持文件属组信息
  -o, --owner 保持文件属主信息
  -r, --recursive 对子目录以递归模式处理。同步目录的时候要加上这个参数
  -l, --links 保留软链结,加上这个参数,同步过来的文件会保持之前的软链接属性不变
  -H, --hard-links 保留硬链结
  -e, --rsh=COMMAND 指定使用rsh、ssh方式进行数据同步
  -z, --compress 对备份的文件在传输时进行压缩处理
  --stats 给出某些文件的传输状态
  --progress 打印同步的过程
  --timeout=TIME 同步过程中,IP超时时间,单位为秒
  --delete 删除那些目标目录中有而源目录中没有的多余文件。这个是rsync做增量方式的全备份的最佳选择方案!!!!!!
  --delete-before 接受者在输出之前进行删除操作。即先将目标目录中文件全部删除,再将源目录文件拷贝过去。这是rsync保持目标目录跟源目录一致的方案!!!
  --delete-after 在同步操作之后做比较,删除那些目标目录中有而源目录中没有的多余文件
  --delete-excluded 删除目标目录中那些被该选项指定排除的文件
  --ignore-errors 即使出现IO错误也进行删除,忽略错误
  --exclude 指定同步时需要过滤掉的文件或子目录(即不需要同步过去的),后面直接跟不需要同步的单个文件名或子目录(不需要跟路径) ,过滤多个文件或子目录,就使用多个--exclude
  --exclude-from 指定同步时需要过滤掉的文件或子目录,后面跟文件(比如/root/exclue.txt),然后将不需要同步的文件和子目录放到/root/exclue.txt下。
  --version 打印版本信息
  --port=PORT 指定其他的rsync服务端口
  --log-format=formAT 指定日志文件格式
  --password-file=FILE 从FILE中得到密码
  --bwlimit=KBPS 限制I/O带宽,KBytes per second
  --existing  只更新目标端已存在的文件
  --ignore-existing   更新目标端不存在的文件
  --remove-source-files   删除源端文件

 环境准备:

属性 备份机 服务器-01 服务器-02
节点 rsyncBak Server-01 Server-02
系统 CentOS Linux release 7.5.1804 (Minimal) CentOS Linux release 7.5.1804 (Minimal) CentOS Linux release 7.5.1804 (Minimal)
内核 3.10.0-862.el7.x86_64 3.10.0-862.el7.x86_64 3.10.0-862.el7.x86_64
SELinux setenforce 0 | disabled setenforce 0 | disabled setenforce 0 | disabled
Firewlld systemctl stop/disable firewalld systemctl stop/disable firewalld systemctl stop/disable firewalld
IP地址 172.16.70.37 172.16.70.181 172.16.70.182

 说明:节点Server-01,Server-02已与rsyncBak实现公钥认证登录。

 设置公钥认证可参考:
   1.Linux下基于OpenSSH 你知道多少?
   2.Linux下如何使用Ansible处理批量操作

Rysnc命令简单使用示例:

例1:本地以及远程shell格式。
[root@Server-01 ~]# rsync /etc/fstab /tmp                # 在本地同步
[root@Server-01 ~]# rsync -r /etc 172.16.10.37:/tmp      # 将本地/etc目录拷贝到远程主机的/tmp下,以保证远程/tmp目录和本地/etc保持同步
[root@Server-01 ~]# rsync -r 172.16.10.5:/etc /tmp       # 将远程主机的/etc目录拷贝到本地/tmp下,以保证本地/tmp目录和远程/etc保持同步
[root@Server-01 ~]# rsync /etc/                          # 列出本地/etc/目录下的文件列表
[root@Server-01 ~]# rsync 172.16.10.5:/tmp/              # 列出远程主机上/tmp/目录下的文件列表

例2:源路径如果是一个目录的话,带上尾随斜线和不带尾随斜线是不一样的。
[root@Server-01 ~]# rsync -a /data /tmp       # 表示的是整个目录包括目录本身
[root@Server-01 ~]# rsync -a /data/ /tmp      # 表示的是目录中的文件,不包括目录本身

例3:如果要拷贝的源路径较长,但只想在目标主机上保留一部分目录结构,例如要拷贝/etc/sysconfig/network-scripts/*到/tmp下,但只想在/tmp下保留从sysconfig开始的目录,如何操作?
[root@Server-01 ~]# rsync -r -R /etc/./sysconfig/network-scripts /tmp
skipping non-regular file "sysconfig/network-scripts/ifdown"
skipping non-regular file "sysconfig/network-scripts/ifdown-isdn"
skipping non-regular file "sysconfig/network-scripts/ifup"
skipping non-regular file "sysconfig/network-scripts/ifup-isdn"
[root@Server-01 ~]# ls /tmp/
sysconfig

例4:可以使用"--backup-dir"指定备份文件保存路径,但要求保存路径必须存在。
[root@Server-01 ~]# rsync -r -R --backup --backup-dir=/tmp/sysconfig_bak /etc/./sysconfig/network-scripts /tmp
skipping non-regular file "sysconfig/network-scripts/ifdown"
skipping non-regular file "sysconfig/network-scripts/ifdown-isdn"
skipping non-regular file "sysconfig/network-scripts/ifup"
skipping non-regular file "sysconfig/network-scripts/ifup-isdn"
[root@Server-01 ~]#
[root@Server-01 ~]# ls /tmp/
sysconfig  sysconfig_bak

例5:排除文件夹或文件,使用 ‘--exclude-from‘ ;
[root@Server-01 ~]# rsync -r -v --exclude-from=‘dir1‘ /data/ /tmp    # 同步/data/目录下所有目录(除/data/dir1目录)

情景一:

  分别将172.16.70.181的/data/mongodbServer01和/data/logServer01目录;172.16.70.182的/data/logServer02和/data/mongodbServer02目录,定期同步到172.16.70.37的/data/backup/hosts目录下。

情景二:

  分别将172.16.70.181的/data/mongodbServer01目录;172.16.70.182的/data/mongodbServer02目录,实时同步到172.16.70.37的/data/backup/momgo目录下。

  即是:172.16.70.181,172.16.70.182 作为rsync的发送端,部署rsync+inotify;172.16.70.37 作为rsync的接收端,只需要安装配置rsync即可,不需要安装inotify。

 

情景一二共同配置:部署源服务器(2台机器同样操作),rsync发送端过程。

[root@Server-01 ~]# yum install -y rsync
[root@Server-01 ~]# rpm -qa | grep rsync
rsync-3.1.2-10.el7.x86_64

[root@Server-01 ~]# systemctl start rsyncd
[root@Server-01 ~]# systemctl enable rsyncd
[root@Server-01 ~]# netstat -nutlp | grep rsync
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      12414/rsync
tcp6       0      0 :::873                  :::*                    LISTEN      12414/rsync

# 创建rsync虚拟账户名和密码,并赋予密码文件600权限
[root@Server-01 ~]# echo "123456" > /etc/rsyncd.passwd
[root@Server-01 ~]# chmod 600 /etc/rsyncd.passwd
[root@Server-01 ~]# ls -l /etc/rsyncd.passwd
-rw-------. 1 root root 20 Jun 30 14:55 /etc/rsyncd.passwd

[root@Server-01 ~]# mkdir /data/{logServer01,mongodbServer01}
[root@Server-01 ~]# ls -l /data/
drwxr-xr-x. 2 root root 6 Jun 30 15:02 logServer01
drwxr-xr-x. 2 root root 6 Jun 30 15:02 mongodbServer01

# 在发送端进行推送/data/logServer01;/data/mongodbServer01测试
[root@Server-01 ~]# rsync -avzP /data/logServer01 rsync_backup@172.16.70.37::log --password-file=/etc/rsyncd.passwd
[root@Server-01 ~]# rsync -avzP /data/mongodbServer01 rsync_backup@172.16.70.37::mongodb --password-file=/etc/rsyncd.passwd

# 在接收端检验是否同步
[root@rsyncBak ~]# ls -l /data/*
/data/logBk:
total 0
drwxr-xr-x. 2 rsync rsync 18 Jun 30 15:10 logServer01

/data/mongodbBk:
total 0
drwxr-xr-x. 2 rsync rsync 17 Jun 30 15:10 mongodbServer01

情景一二共同配置:部署backup服务器,rsync接收端过程。

[root@rsyncBak ~]# rpm -qa | grep rsync
[root@rsyncBak ~]# yum install -y rsync
[root@rsyncBak ~]# rsync --version
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. 

[root@rsyncBak ~]# cp /etc/rsyncd.conf{,.bak}
[root@rsyncBak ~]# vim /etc/rsyncd.conf
......
# 末行新增以下内容
######## 全局配置参数 ##########
uid = rsync
# rsync服务的运行用户,默认是nobody,文件传输成功后属主将是这个uid
gid = rsync
# rsync服务的运行组,默认是nobody,文件传输成功后属组将是这个gid
port = 873
# 指定rsync端口。默认873
fake super = yes
# 无需让rsync以root身份运行,允许接收文件的完整属性
use chroot = no
# rsync daemon在传输前是否切换到指定的path目录下,并将其监禁在内
max connections = 200
# 指定最大连接数量,0表示没有限制
timeout = 300
# 确保rsync服务器不会永远等待一个崩溃的客户端,0表示永远等待
ignore errors
# 忽略某些IO错误信息
auth users = rsync_backup
# 指定连接到该模块的用户列表,只有列表里的用户才能连接到模块,用户名和对应密码保存在secrts file中,这里使用的不是系统用户,而是虚拟用户。不设置时,默认所有用户都能连接,但使用的是匿名连接
secrets file = /etc/rsyncd.passwd
#保存auth users用户列表的用户名和密码,每行包含一个username:passwd。由于"strict modes",默认为true,所以此文件要求非rsync daemon用户不可读写。只有启用了auth users该选项才有效,echo "rsync_backup:123456" > /etc/rsyncd.password  权限:600
read only = false
# 指定该模块是否可读写,即能否上传文件,false表示可读写,true表示可读不可写。所有模块默认不可上传
write only = false
# 指定该模式是否支持下载,设置为true表示客户端不能下载。所有模块默认可下载
list = false
# 客户端请求显示模块列表时,该模块是否显示出来,设置为false则该模块为隐藏模块。默认true
motd file = /var/rsyncd/rsync.motd
# 客户端连接过来显示的消息
pid file = /var/run/rsyncd.pid
# 指定rsync daemon的pid文件
lock file = /var/run/rsync.lock
# 指定锁文件
log file = /var/log/rsyncd.log
# 指定rsync的日志文件,而不把日志发送给syslog
dont compress = *.gz *.tgz *.zip *.z *.Z *.rpm *.deb *.bz2
# 指定哪些文件不用进行压缩传输

########## 模块配置参数,可以创建多个模块 ###########
[backup]
# 模块ID1
path = /data/backup/hosts
# 指定该模块的路径,该参数必须指定。启动rsync服务前该目录必须存在。rsync请求访问模块本质就是访问该路径。
hosts allow = 172.16.0.0/16
# 指定允许连接到该模块的机器,多个ip用空格隔开或者设置区间
hosts deny = 0.0.0.0/32
# 指定不允许连接到该模块的机器

[mongodb]
# 模块ID2
path = /data/backup/mongodb
hosts allow = 172.16.0.0/16
hosts deny = 0.0.0.0/32

# 创建rsync账户及共享目录并修改目录属主为rsync [root@rsyncBak ~]# useradd -M -s /sbin/nologin rsync
[root@rsyncBak ~]# mkdir /data/backup/{hosts,mongodb} -p
[root@rsyncBak ~]# chown -R rsync /data/backup/{hosts,mongodb}
[root@rsyncBak ~]# ls -l /data/backup/
drwxr-xr-x. 2 rsync root 6 Jul  1 10:35 hosts
drwxr-xr-x. 2 rsync root 6 Jul  1 10:35 mongodb
[root@rsyncBak ~]# ls -ld /data/backup/
drwxr-xr-x. 4 root root 30 Jul  1 10:35 /data/backup/

# 创建rsync虚拟账户名和密码,并赋予密码文件600权限
[root@rsyncBak ~]# echo "rsync_backup:123456" > /etc/rsyncd.passwd
[root@rsyncBak ~]# chmod 600 /etc/rsyncd.passwd
[root@rsyncBak ~]# ls -l /etc/rsyncd.passwd
-rw-------. 1 root root 20 Jun 30 12:25 /etc/rsyncd.passwd

# 启动rsync
[root@rsyncBak ~]# systemctl start rsyncd
[root@rsyncBak ~]# systemctl enable rsyncd
[root@rsyncBak ~]# netstat -ntpul | grep rsync
tcp        0      0 0.0.0.0:873             0.0.0.0:*               LISTEN      2665/rsync
tcp6       0      0 :::873                  :::*                    LISTEN      2665/rsync

注意:每次修改配置文件rsyncd.conf后,都需要执行 systemctl restart rsyncd

以下为各情景区别之处。

  • 情景一:部署源服务器(2台机器同样操作),rsync发送端过程。
[root@Server-01 ~]#/data/scripts/backup.sh
#!/bin/bash
#
# 备份解决方案rsync发送端打包脚本

Path=/data/backup
backup_Server=172.16.70.37
local_IP=`ifconfig ens33|awk -F"[ :]+" ‘NR==2{print $3}‘`
Dir=${local_IP}_$(date +%F)

mkdir -p $Path/$Dir
[ -d /data/logServer01 ] && cp -rp /data/logServer01 $Path/$Dir/
[ -d /data/mongodbServer01 ] && cp -rp /data/mongodbServer01 $Path/$Dir/
cd $Path

tar -zcf $Path/${Dir}.tar.gz $Dir

rm -rf $Path/$Dir
# 创建md5sum验证信息
/usr/bin/md5sum $Path/${Dir}.tar.gz > $Path/md5sum_${local_IP}.txt

# 推送打包的文件到备份服务器
rsync -az $Path/ rsync_backup@${backup_Server}::backup --password-file=/etc/rsyncd.passwd

[ $? -eq 0 ] && echo "推送打包文件发送成功." || echo "推送打包文件发送失败.

# 找出超过7天的备份并删除
find $Path/ -name "${local_IP}*" -type f -mtime +7 | xargs rm -rf

# 测试运行同步脚本
[root@Server-01 ~]# bash /data/scripts/backup.sh
推送打包文件发送成功.

# 将脚本挂定时任务
00 04 * * *  root /bin/bash /server/scripts/backup.sh >/dev/null 2>&1
  • 情景一:部署backup服务器,rsync接收端过程。
[root@rsyncBak ~]# cat /data/scripts/rsync_Server.sh
#!/bin/bash
#
# 备份解决方案rsync接收端检查脚本

. /etc/init.d/functions
Path=/data/backup
fileName="md5sum.txt"
# 一共有几台客户端在推送数据
rsync_ClientNum=2

if [ `find $Path/ -type f -name "md5sum*" | wc -l` -eq $rsync_ClientNum ];then
    for filepath in `find $Path/ -type f -name "md5sum*"`
    do
        /usr/bin/md5sum -c $filepath
        if [ $? -eq 0 ];then
            action "${filepath}备份正常!" /bin/true
            rm -rf $filepath
        else
            action "${filepath}备份异常!" /bin/false
            echo "${filepath}备份异常!" | mail -s "$(date +%F)备份检查告警" xxxxxxxx@qq.com
        fi
    done
else
    echo “Rsync客户端推送不完整!”
    echo "Rsync推送不完整" | mail -s "$(date +%F)备份推送告警" xxxxxxxxx@qq.com
fi

# 找出超过180天的不是周1的备份文件并删除
find $Path/ ! -name "*_2.tar.gz" -mtime +180 -type f | xargs rm -rf


# 测试运行同步检查脚本
[root@rsyncBak ~]# bash /data/scripts/rsync_Server.sh
/data/backup/172.16.70.181_2021-07-01.tar.gz: OK
/data/backup/md5sum_172.16.70.181.txt备份正常!            [  OK  ]
/data/backup/172.16.70.182_2021-07-01.tar.gz: OK
/data/backup/md5sum_172.16.70.182.txt备份正常!            [  OK  ]

# 将脚本挂定时任务
00 06 * * * root /bin/bash /data/scripts/rsync_Server.sh >/dev/null 2>&1
  • 情景二:部署源服务器(2台机器同样操作),rsync发送端过程。
# 查看服务器内核是否支持inotify,出现下面的内容,说明服务器内核支持inotify。
[root@rsyncBak ~]# ls -l /proc/sys/fs/inotify/
total 0
-rw-r--r--. 1 root root 0 Jun 30 16:12 max_queued_events
-rw-r--r--. 1 root root 0 Jun 30 16:12 max_user_instances
-rw-r--r--. 1 root root 0 Jun 30 16:12 max_user_watches


# 安装inotify软件
[root@Server-01 ~]# yum install -y inotify-tools
[root@Server-01 ~]# rpm -qa | grep inotify
inotify-tools-3.14-9.el7.x86_64
[root@Server-01 ~]# rpm -ql inotify-tools-3.14-9.el7.x86_64
/usr/bin/inotifywait    # 在被监控的文件或目录上等待特定文件系统事件(open close delete等)发生,执行后处于阻塞状态,适合在shell脚本中使用
/usr/bin/inotifywatch    # 收集被监控的文件系统使用的统计数据,指文件系统事件发生的次数统计。

#命令 man手册说明
    # man inotifywait
    inotifywait - wait for changes to files using inotify  使用inotify进行监控,等待产生变化的文件信息

    # man inotifywatch
    inotifywatch - gather filesystem access statistics using inotify  使用inotify进行监控,收集文件系统访问统计佶息


# 编写脚本实现inotify与rsync相结合
[root@Server-01 ~]# cat /data/scripts/inotify.sh
#!/bin/bash
# 实时检测/data/backup目录内文件是否有变化,如有则同步到172.16.70.37的mongodb模块
#
Path=‘/data‘
# 排查/data目录下以".sh"文件,不需同步
excludefile=‘*.sh‘
backup_Server=172.16.70.37

/usr/bin/inotifywait -mrq --format ‘%w%f‘ -e create,close_write,delete $Path  | while read line
do
    if [ -f $line ];then
        rsync -az $line --delete --exclude=$excludefile rsync_backup@$backup_Server::mongodb --password-file=/etc/rsyncd.passwd
    else
        cd $Path &&        rsync -az ./ --delete --exclude=$excludefile rsync_backup@$backup_Server::mongodb --password-file=/etc/rsyncd.passwd
    fi

done

# 后台运行实时同步脚本
[root@Server-01 ~]# bash /data/scripts/inotify.sh &
[1] 2895

# 创建测试文件
[root@Server-01 ~]# touch  /data/db{1..3} /data/{4..6}.sh
[root@Server-01 ~]# ls -l /data/
-rw-r--r--  1 root root   0 Jul  1 17:24 4.sh
-rw-r--r--  1 root root   0 Jul  1 17:24 5.sh
-rw-r--r--  1 root root   0 Jul  1 17:24 6.sh
-rw-r--r--  1 root root   0 Jul  1 17:24 db1
-rw-r--r--  1 root root   0 Jul  1 17:24 db2
-rw-r--r--  1 root root   0 Jul  1 17:24 db3
  •  情景二:部署backup服务器,rsync接收端过程。
# 检查测试文件是否按要求同步
[root@rsyncBak ~]# ls -l /data/backup/mongodb/
total 0
-rw-r--r--. 1 rsync rsync 0 Jul  1 17:24 db1
-rw-r--r--. 1 rsync rsync 0 Jul  1 17:24 db2
-rw-r--r--. 1 rsync rsync 0 Jul  1 17:24 db3

# 查看后台运行的程序
[root@Server-01 ~]# jobs
[1]+  Running                 bash /data/scripts/inotify.sh &

# 进程的前台和后台的运行方法:
 fg -- 前台
 bg -- 后台

 

Linux下如何使用Rsync备份服务器重要数据

标签:错误   led   remote   思路   oca   备份文件   选项   介绍   rbo   

原文地址:https://www.cnblogs.com/zhangwencheng/p/14949435.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!