rsync 远程同步


正确有效的备份方案是保障系统及数据安全的重要手段,在服务器中通常会结合计划任务,shell脚本来执行本地备份。


rsync(Remote Sync,远程同步)是一个开源的快速安全高效的异地备份工具,可以在不同的主机之间镜像同步整个目录树,支持增量备份,保持链接属性和权限,采用优化的同步算法,传输前执行压缩。适合异地备份,镜像服务等应用,是一种常用的文件备份工具及数据同步工具。

官方站点:http://rsync.samba.org 

维护人员:Waync Davison(和samba维护人员一样)

版本:3.0.9

发起端(客户端):负责发起rsync同步操作的机器称为发起端

备份源(服务器):负责响应来自发起端rsync同步操作的机器称为备份源


下载:在下行同步中,备份源负责提供文档的原始位置,发起端应对操作文件具有读取权限

上传:在上行同步中,备份源负责提供文档的目标位置,发起端应对操作文件具有写入权限

rsync 两种源模式:


当源路径或目的路径的主机名后面包含一个冒号分隔符时,rsync使用远程shell传输;当源路径或目的路径的主机名后面包含两个冒号,或使用rsync://URL时,rsync使用TCP直接连接rsync daemon

SSH备份源(scp)

rsync备份源(自己作为守护进程)

1. 配置SSH备份源

====================================================================================================================

优点:

1,rsync可以再中断传输之后恢复传输

2,rsync只传输源文件和目标文件之间不一致的部分
3,rsync可以执行完整或增量备份
4,可以使用基于ssh等方式传输文件
5,可以保持原有文件的所有属性信息

配置过程:

a、确认备份源文件夹位置

b、准备备份操作用户

c、配置用户权限

案例:

    A机器的网站目录/var/www/html作为备份源

    用户down做下载操作

    用户up做上传操作

rsync备份源 IP:192.168.8.80

rsync发起端 IP:192.168.8.20

A机器上的操作:192.168.8.80:

[root@server ~]# yum -y install httpd 

[root@server ~]# useradd down

[root@server ~]# echo "123456" | passwd --stdin down

更改用户 down 的密码 。

passwd: 所有的身份验证令牌已经成功更新。

[root@server ~]# useradd up

[root@server ~]# echo "123456" | passwd --stdin up

更改用户 up 的密码 。

passwd: 所有的身份验证令牌已经成功更新。

[root@server ~]# vim /etc/ssh/sshd_config 

122 UseDNS no    //关闭UseDNS加速SSH登录

spacer.gifwKiom1e-lMSgMitJAAAP4_FYOSc805.png-wh_50[root@server ~]# service sshd restart

停止 sshd:                                             [确定]

正在启动 sshd:                                         [确定]

调整/var/www/html目录权限:

    down用户有读取权限

    up用户有写入权限,建议将目录的属主修改为up

    另外需要为web服务的运行用户apache指定额外的权限

[root@server ~]# chown -R up:up /var/www/html/

[root@server ~]# setfacl -R -m user:apache:rwx /var/www/html/ 

[root@server ~]# getfacl /var/www/html/

getfacl: Removing leading '/' from absolute path names

# file: var/www/html/

# owner: up

# group: up

user::rwx

user:apache:rwx

group::r-x

mask::rwx

other::r-x

[root@server ~]# mkdir /var/www/html/dir{1..10}

以后在/var/www/html/新建立的文档,apache用于都具有rwx权限

[root@server ~]# setfacl -R -m default:user:apache:rwx /var/www/html/

[root@server ~]# getfacl /var/www/html/ |grep default

getfacl: Removing leading '/' from absolute path names

default:user::rwx

default:user:apache:rwx

default:group::r-x

default:mask::rwx

default:other::r-x

acl访问控制机制参数详解

setfacl    设置acl权限

getfacl    查看acl权限

-R    递归

-m    制定权限

-x    个别删除

-b  全部删除

* 下面两行不需要执行,作为了解

setfacl -R -b /var/www/html                    表示删除所有ACL属性

setfacl -R -x user:apache /var/www/html/    只删除某一项

====================================================================================================================

2. 配置rsync备份源

====================================================================================================================

rsync 工具不仅用作远程同步发起端(客户端),也可以作为守护进程(服务端),为其他客户机提供备份源。

1、建立/etc/rsyncd.conf配置文件

2、为备份账户创建数据文件

3、启动rsync服务进程

1、建立/etc/rsyncd.conf配置文件,以备份源目录 /var/www/html/,备份帐号:backuper作为案例:

[root@server ~]# yum -y install rsync

[root@server ~]# vim /etc/rsyncd.conf     //注:文件名rsyncd.conf必须加d

uid = nobody

gid = nobody

use chroot = yes

address = 192.168.8.80

port = 873

log file = /var/log/rsyncd.log

pid file = /var/run/rsyncd.pid

hosts allow = 192.168.8.0/24

[wwwroot]

        path = /var/www/html

        comment = Document Root

        read only = yes

        dont compress = *.gz *.bz2 *.tgz *.zip *.rar *.z

        auth users = backuper

        secrets file = /etc/rsyncd_users.db

uid = nobody                                                //用户名

gid = nobody                                                //组名

use chroot = yes                                            //禁锢在源目录

address = 192.168.8.80                                    //监听地址

port = 873                                                    //监听端口

log file = /var/log/rsyncd.log                                //日志文件位置

pid file = /var/run/rsyncd.pid                                //存放进程ID文件位置

hosts allow = 192.168.8.0/24                                //允许访问的客户端地址

[wwwroot]                                                    //共享模块名称

        path = /var/www/html                                //源目录的实际路径

        comment = Document Root        //描述信息

        read only = yes                                        //是否为只读

        dont compress = *.gz *.bz2 *.tgz *.zip *.rar *.z    //同步时不再压缩的文件类型

        auth users = backuper                                //备份授权用户

        secrets file = /etc/rsyncd_users.db                    //存放账户信息的数据文件

对于rsync的备份源最好仅允许以只读的方式做下行同步

若需要做上行同步时,建议用SSH备份源

下行同步可采用匿名的方式,只要去掉auth users 、secrets file 配置记录即可        

2、为备份账户创建数据文件,以冒号分割,密码信息在文件中以明文方式存放,为避免信息泄漏,需要调整权限

[root@server ~]# vim /etc/rsyncd_users.db

backuper:123456

[root@server ~]# chmod 600 /etc/rsyncd_users.db 

备份用户backuper也需要对/var/www/html/有相应的读取权限

[root@server ~]# ll -d /var/www/html/

drwxrwxr-x+ 14 up up 4096 6月  20 10:14 /var/www/html/

3、启动服务,运行参数为"--daemon",关闭rsync可采用kill命令

[root@server ~]# rsync --daemon

[root@server ~]# netstat -anpt | grep rsync

tcp        0      0 192.168.8.80:873            0.0.0.0:*                   LISTEN      4844/rsync

关闭服务

[root@server ~]# kill $(cat /var/run/rsyncd.pid)

4、异地备份的特殊性,需要全天不间断运行,配置成只有客户机连接的时候才启动(交给xinetd管理)

[root@server ~]# yum -y install xinetd

[root@server ~]# vim /etc/xinetd.d/rsync

6  disable = no                    #将原有的yes改成no

12 server_args     = --daemon    #确认有--daemon选项即可

spacer.gifwKioL1e-lUOTTsZlAAA-gJy7900703.png

[root@server ~]# service xinetd restart

停止 xinetd:                                           [确定]

正在启动 xinetd:                                       [确定]

====================================================================================================================

使用rsync备份工具(在客户机,发起端执行)

本地备份:备份源和发起端可以是一台机器

[root@client ~]# mkdir /yongshi

[root@client ~]# rsync /etc/fstab /yongshi

[root@client ~]# rsync -rl /etc/fstab /boot/grub /yongshi

rsync的常用格式:

rsync [选项] 原始位置 目标位置

-r:递归模式,包含目录及子目录中所有文件

-l:对于符号链接文件仍然复制为符号链接文件

-p:保留文件的权限标记

-t:保留文件的时间标记

-g:保留文件的属组标记(仅超级用户使用)

-o:保留文件的属主标记(仅超级用户使用)

-D:保留设备文件及其他特殊文件

-a:归档模式,递归并保留对象属性,等同于 -rlptgoD

-v:显示同步过程的详细(verbose)信息

-z:在传输文件时进行压缩(compress)

-H:保留硬连接文件

-A:保留ACL属性信息

--delete:删除目标位置有而原始位置没有的文件

--checksum:根据对象的校验和来决定是否跳过文件

异地备份:

B机器上的操作:192.168.8.20

====================================================================================================================

配置源的表示方法:

rsync命令需要指定备份源服务器中的资源位置

下行备份操作:备份源对应 “原始位置”

上行备份操作:备份源对应 “目标位置”

[root@client ~]# yum -y install rsync

SSH备份源表示为:

用户名@主机地址:目标路径,多个路径用一个冒号分割

注:此方法类似scp用户名必须是系统中存在的一个用户不能是上面的backuper用户

访问SSH备份源,下载到本地/opt目录

[root@client ~]# rsync -avz down@192.168.8.80:/var/www/html/ /yongshi

Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

down@192.168.8.80's password:   123456

receiving incremental file list

./

btcom/

btcom/index.html

dir1/

dir10/

dir2/

dir3/

dir4/

dir5/

dir6/

dir7/

dir8/

dir9/

testcom/

testcom/index.html

sent 100 bytes  received 448 bytes  5.99 bytes/sec

total size is 24  speedup is 0.04

[root@client ~]# ls /yongshi/

btcom  dir10  dir3  dir5  dir7  dir9   grub

dir1   dir2   dir4  dir6  dir8  fstab  testcom

------------------------------------------------------

rsync备份源表示为:

方式一:用户名@主机地址::共享模块名称

rsync -avz backuper@192.168.8.80::wwwroot /yongshi

方式二:rsync://用户名@主机地址/共享模块名称

rsync -avz rsync://backuper@192.168.8.80/wwwroot /tmp

以上两种方法的用户可以是虚拟用户不存在于系统中

====================================================================================================================

1、下行同步,ssh备份源

将服务器的/var/www/html文件夹与本地/yongshi文件夹同步(保持文件权限属性,软硬连接,ACL属性,删除/yongshi中多余文件,传输过程进行加密)

[root@client ~]# mkdir /yongshi/acb

[root@client ~]# rsync -avzAH --delete down@192.168.8.80:/var/www/html/ /yongshi/

down@192.168.8.80's password:   123456

receiving incremental file list

deleting acb/

./

btcom/

dir1/

dir10/

dir2/

dir3/

dir4/

dir5/

dir6/

dir7/

dir8/

dir9/

testcom/

sent 68 bytes  received 404 bytes  5.27 bytes/sec

total size is 24  speedup is 0.05

[root@client ~]# ls /yongshi/

btcom  dir10  dir3  dir5  dir7  dir9

dir1   dir2   dir4  dir6  dir8  testcom

对于同一项远程同步任务,再次执行时,自动做增量更新,同名的文件将不再重复复制

在服务器上的操作:192.168.8.80:

[root@server ~]# cd /var/www/html/

[root@server html]# for i in {1..10}; do touch $i.txt; done

[root@server html]# ls

10.txt  3.txt  6.txt  9.txt  dir10  dir4  dir7  testcom

1.txt   4.txt  7.txt  btcom  dir2   dir5  dir8

2.txt   5.txt  8.txt  dir1   dir3   dir6  dir9

客户端上的操作:192.168.8.20:

[root@client ~]# rsync -avzAH --delete down@192.168.8.80:/var/www/html/ /yongshi/

Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

down@192.168.8.80's password:  123456

receiving incremental file list

./

1.txt

10.txt

2.txt

3.txt

4.txt

5.txt

6.txt

7.txt

8.txt

9.txt

sent 216 bytes  received 943 bytes  331.14 bytes/sec

total size is 24  speedup is 0.02

[root@client ~]# ls /yongshi/

10.txt  3.txt  6.txt  9.txt  dir10  dir4  dir7  testcom

1.txt   4.txt  7.txt  btcom  dir2   dir5  dir8

2.txt   5.txt  8.txt  dir1   dir3   dir6  dir9

====================================================================================================================

2、下行同步rsync备份源

当备份源为rsync服务器时,只要将同步操作中的原始位置修改为规范格式,其他操作基本一样

将备份源服务器中的 wwwroot下载到本地的 /myweb目录

客户端上的操作:192.168.8.20:

[root@client ~]# mkdir /myweb

[root@client ~]# rsync -avzAH --delete backuper@192.168.8.80::wwwroot /myweb 

Password:  123456

receiving incremental file list

./

1.txt

10.txt

2.txt

3.txt

4.txt

5.txt

6.txt

7.txt

8.txt

9.txt

btcom/

btcom/index.html

dir1/

dir10/

dir2/

dir3/

dir4/

dir5/

dir6/

dir7/

dir8/

dir9/

testcom/

testcom/index.html

sent 340 bytes  received 1132 bytes  37.27 bytes/sec

total size is 24  speedup is 0.02

[root@client ~]# ls /myweb/

10.txt  3.txt  6.txt  9.txt  dir10  dir4  dir7  testcom

1.txt   4.txt  7.txt  btcom  dir2   dir5  dir8

2.txt   5.txt  8.txt  dir1   dir3   dir6  dir9

====================================================================================================================

3、上行同步ssh备份源

将客户机中的文件上传到备份源服务器的/var/www/html目录下,由于用户是up并非root用户,因此 -g -o 等选项无法使用

[root@client ~]# rsync -rlvz install.log up@192.168.8.80:/var/www/html

Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

up@192.168.8.80's password:  123456

[root@client ~]# rsync -rlvz install.log up@192.168.8.80:/var/www/html

Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

up@192.168.8.80's password: 

sending incremental file list

install.log

sent 70 bytes  received 31 bytes  15.54 bytes/sec

total size is 0  speedup is 0.00


查看备份源服务器

[root@server html]# pwd 

/var/www/html

[root@server html]# ls

10.txt  3.txt  6.txt  9.txt  dir10  dir4  dir7  install.log

1.txt   4.txt  7.txt  btcom  dir2   dir5  dir8  testcom

2.txt   5.txt  8.txt  dir1   dir3   dir6  dir9

====================================================================================================================

编写rsync备份脚本:

生产环境中的备份工作通常是按计划重复执行的,结合shell和crond服务来完成

1、ssh备份源的无交互验证,由于脚本根据crond时间来执行,用户没办法按时根据提示输入密码

B机器上的操作:192.168.8.20:创建密钥对,将公钥文件发给A服务器中的备份用户,实现无交互登录

创建密钥对:

[root@client ~]# ssh-keygen -t rsa

Generating public/private rsa key pair.

Enter file in which to save the key (/root/.ssh/id_rsa):     //一路回车

Enter passphrase (empty for no passphrase):           //一路回车

Enter same passphrase again:                                     //一路回车

Your identification has been saved in /root/.ssh/id_rsa.

Your public key has been saved in /root/.ssh/id_rsa.pub.

The key fingerprint is:                                        

60:da:54:08:1d:5d:af:91:d5:34:9a:59:af:a9:4a:37 root@client

The key's randomart p_w_picpath is:

+--[ RSA 2048]----+

|    .o.+... .o+  |

|      o..  + =.o |

|      +   o =   .|

|     = .   o   o |

|    . . S .   o  |

|             .   |

|          . E    |

|         . o .   |

|          .      |

+-----------------+

复制密钥对:

[root@client ~]# ssh-copy-id -i down@192.168.8.80

[root@client ~]# ssh-copy-id -i up@192.168.8.80

连接测试:

[root@client ~]# ssh down@192.168.8.80

[root@client ~]# ssh up@192.168.8.80

[root@client ~]# rm -rf /yongshi/*

[root@client ~]# rsync -avzH --delete down@192.168.8.80:/var/www/html/ /yongshi

Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!  (这是ssh连接报警解决方法如下)

receiving incremental file list

./

1.txt

10.txt

2.txt

3.txt

4.txt

5.txt

6.txt

7.txt

8.txt

9.txt

install.log

btcom/

btcom/index.html

dir1/

dir10/

dir2/

dir3/

dir4/

dir5/

dir6/

dir7/

dir8/

dir9/

testcom/

testcom/index.html

sent 309 bytes  received 1097 bytes  26.78 bytes/sec

total size is 24  speedup is 0.02


解决ssh连接报警


Address 192.168.8.80 maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!

[root@client ~]# vim /etc/ssh/ssh_config 

开启此行,取消注释

spacer.gifwKiom1e-lY7zEEAXAAAahswd4Io095.png-wh_50

[root@client ~]# service sshd restart

停止 sshd:                                                [确定]

正在启动 sshd:                                            [确定]

测试

[root@client ~]# rsync -avzH --delete down@192.168.8.80:/var/www/html/ /yongshi

receiving incremental file list

sent 23 bytes  received 558 bytes  1162.00 bytes/sec

total size is 24  speedup is 0.04

====================================================================================================================

2、rsync备份源的无交互验证,可以使用export RSYNC_PASSWORD保存密码,脚本执行时,可以自动读取该变量的值,在需要时发送给rsync服务器来进行验证

export RSYNC_PASSWORD=123456

rsync -avzAH --delete backuper@192.168.8.80::wwwroot /wwwroot/

相对于 SSH 源的免交互措施来说,使用变量存放密码显得不够安全,因此可在脚本中使用,并将脚本的权限严格控制,避免密码泄漏。

vi rsync_get_wwwroot.sh 

-------------------------------------

#!/bin/bash

CMD="/usr/bin/rsync"

RSYNC_USER="backuper"

export RSYNC_PASSWORD="123456"

ARGS="-avzAH --delete"

SRC="192.168.8.80::wwwroot"

DST="/wwwroot"

if [ ! -d $DST ]

then

    mkdir -p $DST

fi

$CMD $ARGS $RSYNC_USER@$SRC $DST

------------------------------------

chmod 700 rsync_get_wwwroot.sh

crontab -e

30 20 * * * /root/rsync_get_wwwroot.sh

service crond restart

chkconfig crond on

====================================================================================================================

rsync+inotifys实现实时同步(server端主动上传文件到client端) 


Linux 从2.6.13版内核开始提供了inotify通知接口,用来监控文件系统的各种变化情况,如文件的存取,删除,移动,修改内容,修改属性等操作。利用这个机制,可以实现文件异动警告,增量备份,针对目录或文件的变化及时做出响应。

rsync+inotify 可以实现触发式备份,只要原始位置的文档发生变化,则立即启动增量备份,否则处于静默等待状态,避免了按固定周期备份时存在的延迟性,周期过密等问题。

inotify 主要做本机监控,在触发式备份应用中更适合上行同步

inotify机制提供了三个调控参数:

cat /proc/sys/fs/inotify/max_queued_events     //表示监控事件队列(16384)

16384

cat /proc/sys/fs/inotify/max_user_instances    //最多监控实例数(128)

128

cat /proc/sys/fs/inotify/max_user_watches     //每个实例最多监控文件数(8192)

8192

当要监控的目录,文件数量较多或者变化频繁时,建议加大这三个参数的值


在/etc/sysctl.conf文件里添加一下三行

[root@server ~]# vim /etc/sysctl.conf

fs.inotify.max_queued_events = 16384

fs.inotify.max_user_instances = 1024              

fs.inotify.max_user_watches = 1048576

wKiom1e-lbCiELsDAAAXBlQVF9Y420.png

[root@server ~]# sysctl -p

安装 inotify-tools 主要提供inotifywait,inotifywatch等工具,用来监控,汇总改动情况

官方站点:http://inotify-tools.sourceforge.net

[root@server ~]# tar xf inotify-tools-3.14.tar.gz -C /usr/src/

[root@server ~]# cd /usr/src/inotify-tools-3.14/

[root@server inotify-tools-3.14]# ./configure && make && make install

以监控网站目录/var/www/html为例,在端口(pts/0)中执行inotifywait命令后,跟踪屏幕输出结果

[root@server ~]# inotifywait -mrq -e modify,create,move,delete,attrib /var/www/html/

-e    指定要监控的事件

-m    表示持续监控

-r    表示递归整个目录

-q    简化输出信息

inotifywait 可监控modify(修改),create(创建),move(移动),delete(删除),attrib(属性更改)等各种事件,一有变动立即输出结果,inotifywait可用于收集系统变动情况,并在运行结束后输出汇总的变化情况。


在另外一个终端(pts/1)中改动/var/www/html目录下的内容

[root@ns1 ~]# mkdir /var/www/html/dira

[root@ns1 ~]# mkdir /var/www/html/dirb

[root@ns1 ~]# mv /var/www/html/dirb /var/www/html/dirc

[root@ns1 ~]# rm -rf /var/www/html/dira


回到监控终端窗口(pts/0)查看输出信息

[root@server ~]# inotifywait -mrq -e modify,create,move,delete,attrib /var/www/html/

/var/www/html/ CREATE,ISDIR dira

/var/www/html/ CREATE,ISDIR dirb

/var/www/html/ MOVED_FROM,ISDIR dirb

/var/www/html/ MOVED_TO,ISDIR dirc

/var/www/html/ DELETE,ISDIR dira

编写触发式同步脚本

inotifywait 输出的监控结果中,每行记录中包括目录,事件,文件,据此可以识别变动情况,只要检测到变动时执行rsync上行同步操作即可。

注意:当更新较频繁时,避免并发执行rsync备份,若rsync进程已经存在则忽略本次同步,或者根据rsync进程数量来决定是否同步

[root@server ~]# vi /opt/bak_transfer.sh    

#!/bin/bash

INOTIFY_CMD="inotifywait -mrq -e modify,create,move,attrib,delete /var/www/html/"

RSYNC_CMD="rsync -avzAH --delete /var/www/html/ up@192.168.8.20:/yongshi"

$INOTIFY_CMD | while read DIRECTORY EVENT FILE

do

        if [ $(pgrep rsync | wc -l) -le 0 ]

        then

                $RSYNC_CMD

        fi

done


注:1.另一台上必须存在up用户

       2.生成了秘钥对验证

       3.up用户对/yongshi目录具有写权限(w)


[root@server ~]# chmod +x /opt/bak_transfer.sh

[root@server ~]# echo "/bin/bash /opt/bak_transfer.sh" > /etc/rc.local

[root@server ~]# /opt/bak_transfer.sh 


脚本用来测试本机/var/www/html目录的变动,一旦有更新立刻出发rsync同步操作,上传至服务器192.168.8.20的/yongshi目录,用户验证采用SSH方式。

1、使用rsync工具执行一次上行同步

2、在本机运行bak_transfer.sh脚本

3、在本机的/var/www/html目录下,执行创建,删除,修改等操作

4、查看服务器中的/var/www/html目录中的变化

1.ssh源配置

2.rsync源配置

3.测试ssh源配置

4.测试rsync源配置

5.将ssh和rsync做成免密码

6.rsync+inotify 实现自动