18.7 使用rsync备份

Remote Synchronize简称rsync,这是一款可以远程同步文件的软件,同步过程采用rsync加密算法保证了文件安全,并且同步的文件可保持原文件的属性(比如权限、时间等)不变。

首先准备两台服务器作为实验环境,按照以下步骤搭建实验环境。

服务器A:配置为rsync服务器(假设IP为192.168.61.130)。


#

安装rsync

软件

[root@localhost ~]# yum install rsync

#

安装xinetd

[root@localhost ~]# yum yum install xinetd

#

配置xinetd

、rsync

开机自启动

[root@localhost ~]# chkconfig xinetd on

[root@localhost ~]# chkconfig rsync on

#

手工创建rsync

的配置文件etcrsyncd.conf

[root@localhost ~]# cat etcrsyncd.conf

uid = root

gid = root

use chroot = no

max connections = 10

strict mode = yes

port = 873

[backup]

path = /root

comment = Root Dir

ignore errors

read only = yes

list = no

auth users = john

secret file = etcrsync.sec

#

配置密码文件etcrsync.sec

并授予600

权限

[root@localhost ~]# cat etcrsync.sec

john:wang001

[root@localhost ~]# chmod 600 etcrsync.sec

#

重启xinetd

以激活rsync

[root@localhost ~]# service xinetd restart

#

确认rsync

已经运行

[root@localhost ~]# netstat -a | grep rsync

tcp 0 0 :rsync :* LISTEN


服务器B:配置为rsync客户端(假设IP为192.168.61.131)。


#

安装rsync

软件

[root@localhost ~]# yum install rsync

#

配置rsync

客户端密码文件并授予600

权限

[root@localhost ~]# cat etcrsync.sec

wang001

[root@localhost ~]# chmod 600 etcrsync.sec

#

创建目录rootrsync_dir

,用于同步服务器A[backup]

模块中的文件

[root@localhost ~]# mkdir rsync_dir

#

测试同步,把服务器A/root

目录中的全部文件同步到本地rootrsync_dir

目录

[root@localhost ~]# rsync -vzrtopg —progress —delete john@192.168.61.130::backup

rootrsync_dir —password-file=etcrsync.sec


最后脚本化以上rsync过程,增加服务器是否存活的判断,并增加日志使rsync过程更加清晰,这样便于在运行出错时排查问题。


  1. #!/bin/bash

  2. RSYNC_SERVER=192.168.61.130

  3. RSYNC_USER=john

  4. RSYNC_MODULE=backup

  5. RSYNC_PASS=etcrsync.sec

  6. RSYNC_LOG=/var/run/rsync.log

  7. LOCAL_DIR=rootrsync_dir

  8. RSYNC=/usr/bin/rsync

  9. PING=/bin/ping

  10. run_rsync() {

  11. echo "Starting Rsync at `date`" | tee -a $RSYNC_LOG

  12. $RSYNC -vzrtopg --progress --delete $RSYNC_USER@$RSYNC_SERVER::$RSYNC_

  13. MODULE $LOCAL_DIR --password-file=$RSYNC_PASS

  14. echo "Rsync Finished at `date`" | tee -a $RSYNC_LOG

  15. }

  16. test_alive() {

  17. $PING $RSYNC_SERVER -c 3 -w 3

  18. if [ $? -ne 0 ]; then

  19. echo "Server down at `date`" >> $RSYNC_LOG

  20. exit 1

  21. fi

  22. }

  23. test_alive > devnull 2>&1

  24. run_rsync