rsync+inotify实现实时同步acgred.cn

一、无差异同步数据

1.首先,在实践实时同步之前我们先来了解一下rsync无差异同步
无差异推送数据加–delete

1)备份 –delete风险
本地有,远端就有。本地没有远端有也会删除,服务器端的目录数据可能会丢失

无差异拉取数据 www.gaimor.cn

2)代码发布、下载 –delete风险
远端有,本地就有。远端没有的本地有也会删除,本地的目录数据可能丢失

未分类

ps:上图会将远程端的/hzftp/test里的文件完全克隆到客户端的/data1目录中


多模块共享配置,只需新增模块目录地址即可,其他 www.acgred.cn


inotify实施(切记在客户端上安装)

前提:需要rsync daemon已经搭建完成的情况下,可以在服务端上推拉数据
inotifu安装:
检查服务端的rsync服务是正常启用的,并且可以在客户端往服务端推送文件
检查内核版本:uname -r

[root@localhost inotify]# ls 
max_queued_events  max_user_instances  max_user_watches
[root@localhost inotify]# ll /proc/sys/fs/inotify
总用量 0
-rw-r--r--. 1 root root 0 6月  27 22:58 max_queued_events   
-rw-r--r--. 1 root root 0 6月  27 22:58 max_user_instances  
-rw-r--r--. 1 root root 0 6月  27 22:58 max_user_watches

然后从互联网上下载inotify源码安装包
下载好后,解压:tar xf inotify-tools-3.14.tar.gz

cd inotify-tools-3.14
./configure --prefix=/usr/local/inotify-tools-3.14
make && make install
ln -s /usr/local/inotify-tools-3.14 /usr/local/inotify
[root@localhost inotify]# ll /usr/local/inotify
总用量 4
drwxr-xr-x. 2 root root   43 6月  27 23:10 bin  #inotify执行命令
drwxr-xr-x. 3 root root   25 6月  27 23:10 include  #inotify所需头文件
drwxr-xr-x. 2 root root 4096 6月  27 23:10 lib  #动态链接库文件
drwxr-xr-x. 4 root root   26 6月  27 23:10 share   #帮助文档

使用inotify来监控目录文件,当被监控的目录发生变化会产生输出:
监听创建:create
监听删除:delete
监听写入:close_write
ps:当create和close_write同时使用时,创建文件会被监控两遍
======create,delete,close_write同时使用用逗号隔开=======
/usr/local/inotify-tools-3.14/bin/inotifywait -mrq --timefmt '%d%m%y %H:%M' --format '%T %w%f' -e create /backup

未分类

开发inotify数据同步脚本
创建脚本存放路径:mkdir -p /server/scripts
进入脚本存放目录:cd /server/scripts

CentOS安装和配置Rsync进行文件同步

Liunx系统实现文件同步不需要搭建FTP这类的工具,只需要按照Rsync配置下文件就可以。

本文以Centos7.0为例。

1.首先关闭SELINUX(不关闭无法同步,权限太高了)

vi /etc/selinux/config #编辑防火墙配置文件
#SELINUX=enforcing #注释掉
#SELINUXTYPE=targeted #注释掉
SELINUX=disabled #增加
:wq! #保存,退出
setenforce 0  #立即生效

2.服务端和客户端同时安装Rsync

yum install rsync xinetd #安装

3.客户端和服务端同时新增配置文件(centos7 默认没有了,得单独手工建,否则无法启动)

vim /etc/xinetd.d/rsync
service rsync
{
        disable              = no
        flags                  = IPv6
        socket_type      = stream
        wait                   = no
        user                   = root
        server                = /usr/bin/rsync
        server_args       = --daemon
        log_on_failure  += USERID
}

4.修改服务端配置给客户端调用

vim /etc/rsyncd.conf
log file = /var/log/rsyncd.log #日志文件位置,启动rsync后自动产生这个文件,无需提前创建

pidfile = /var/run/rsyncd.pid  #pid文件的存放位置

lock file = /var/run/rsync.lock  #支持max connections参数的锁文件

secrets file = /etc/rsync.pass  #用户认证配置文件,里面保存用户名称和密码,后面会创建这个文件

motd file = /etc/rsyncd.Motd  #rsync启动时欢迎信息页面文件位置(文件内容自定义)

[test] #自定义名称

path = /data/ #rsync服务端数据目录路径

comment =rsync data comment #对那个文件夹进行描述

uid = root #设置rsync运行权限为root 推荐使用 nobody

gid = root #设置rsync运行权限为root 推荐使用 nobody

port=873  #默认端口

use chroot = no #默认为true,修改为no,增加对目录文件软连接的备份

read only = no  #设置rsync服务端文件为读写权限

list = no #不显示rsync服务端资源列表

max connections = 200 #最大连接数

timeout = 600  #设置超时时间

auth users = test #执行数据同步的用户名,可以设置多个,用英文状态下逗号隔开

hosts allow = 192.168.21.129  #允许进行数据同步的客户端IP地址,可以设置多个,用英文状态下逗号隔开

hosts deny = 192.168.21.254 #禁止数据同步的客户端IP地址,可以设置多个,用英文状态下逗号隔开

5.新增同步用户的配置文件保存密码

vim /etc/rsync.pass
test:123456

6.对配置文件进行授权

chmod 600 /etc/rsyncd.conf  #设置文件所有者读取、写入权限
chmod 600 /etc/rsync.pass  #设置文件所有者读取、写入权限

7.重启Rsync 是用软件生效

systemctl restart xinetd

8.客户端开始同步

首先telnet端口:
telnet 172.16.120.18 83 

服务端同步文件到客户端:
rsync -avz  [email protected]::ftp  /data


客户端同步文件到服务端

rsync -av /data/  [email protected]:ftp 

其中/data/ 若后面不加”/” 那/data 就是表示本身同步过去,切记!

Rsync 数据同步工具应用指南

Rsync 简介

Rsync 是一款开源的,快速的,多功能的,可实现全量及增量(差异化备份)的本地或远程数据同步备份的优秀工具。

Rsync软件适用于Unix、Linux、Windows等多种操作系统。

1)可使本地和远程两台主机之间的数据快速复制同步镜像,远程备份的功能,这个功能类似ssh带scp命令,但又优于scp命令的功能,scp每次都是全量拷贝,而rsync可以增量拷贝。

2)rsync还可以在本地主机的不同分区或目录之间全量及增量的复制数据,

3)利用rsync还可以实现删除文件和目录的功能。相当于rm

4)rsync相当于scp,cp.rm但是还优于他们每一个命令。

在同步备份数据时,默认情况下rsync通过独特的“quick check” 算法,它仅同步大小或者最后修改时间发生变化的文件或目录,当然也可以是根据权限,属主等属性的变化同步,但需要指定相应的参数,甚至可以实现只同步一个文件里有变化的内容部分,所以可以实现快速的同步备份数据。

  • CentOS 5 rsync2.x 比对方法,把所有的文件比对一遍,然后进行同步。

  • CentOS 6 rsync3.x 比对方法,一边比对差异,一边对差异的部分进行同步。

Rsync 特性

1)支持拷贝特殊文件如链接文件,设备等。

2)可以有排除指定文件或目录同步的功能,相当于打包命令tar的排除功能。

3)可以做到保持源文件或目录的权限,时间,软硬链接,属主,组等属性均不改变 -p.

4)可以实现增量同步,即只同步发生变化的数据,因此数据传输的效率很高,tar -N.

5)可以使用rcp,rsh,ssh,等方式来配合传输文件(rsync本身不对数据加密)

6)可以通过soket(进程方式)传输文件和数据(服务端和客户端)*****

7)支持匿名的或认证的(无需系统用户)的进程模式传输,可实现方便安全的进程数据备份及镜像。

实时同步(解决存储服务器等单点问题)

利用rsync结合inotify的功能做实时的数据同步,根据存储服务器上目录的变化,把变化的数据通过inotify或sersync结合rsync命令,同步到备份服务器,还可以通过drbd方案以及双写的方案实现双机数据同步。

Rsync的工作方式

大致使用三种主要的传输数据的方式。

1)单个主机本地之间的数据传输(此时类似于cp命令的功能)

2)借助rcp,ssh等通道来传输数据(此时类似于scp命令的功能)

3)以守护进程(socket)的方式传输数据(这个是rsync自身的重要功能)

服务端与客户端安装 Rsync

修改主机名

hostname backup
vi /etc/sysconfig/network

安装 rsync 与 依赖

yum -y install rsync xinetd

vi /etc/xinetd.d/rsync

将yes 修改为no IPV6修改为IPV4

rsync 命令同步参数详解

local(本地)模式的命令参数

-v --verbose 详细模式输出,传输时的进度等信息。

-z --compress 传输时进行压缩以提高传输效率,--compress-level=NUM可按级别压缩

重要的命令

-a --archive 归档模式,表示以递归方式传输文件,并保持所有文件属性,等价于-rtopgDl

-r 对子目录以递归模式,即目录下的所有目录都同样传输,注意是小写的r.

-o 保持文件属性信息

-p 保持文件权限

-g 保持文件属组信息

-P 显示同步的过程及传输时的进度等信息

-D 保持设备文件信息

-l 保持软连接


-avzP 提示:这里的 相当于 -vzrtopgDlP(还多了Dl功能)生产环境常用 

-avz 定时任务就不用输出过程了可以-az

需了解的命令

-e 使用的信道协议,指定替代rsh的shell程序,例如:ssh

--exclude=PATTERN 指定排除不需要传输的文件模式(和tar参数一样)

--exclude=file(文件名所在的目录文件)(和tar参数一样)

--delete 让目标目录SRC和源目录数据DST一致。

注意:/tmp/ rsync如果tmp/ 加上斜线的话就表示只选中斜线后的文件,不包含tmp。

如果不加上斜线 tmp 那么就是包含目录本身和目录之下的文件。

做数据同步容易将带宽占满,导致网站无法访问

rsync scp ftp 都有限速功能

解决:man rsync里面有一个限速的参数。

我之前刚做运维的时候,在备份数据时,没考虑业务低谷时间点,将带宽占满了,导致网站无法正常访问。发现问题之后,我立即停止数据备份,然后man 了一下,才发现rsync有限速参数。

尽量不要在业务高并发的时候做备份,要在业务低谷时间段进行,限速备份。

当然,scp,ftp都有限速的功能。

借助ssh通道在不同主机之间传输数据

man rsyncd.conf

使用-e参数,利用ssh隧道进行文件传输
[root@backup ~]# rsync -avz /etc/hosts -e 'ssh -p 22' [email protected]:/mnt

可以使用ssh key 免密钥登录,然后可以做定时任务。

优化ssh (让连接服务器进行rsync更快)

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

GSSAPIAuthentication no   (把这个的注释去掉,也就是打开)
#GSSAPIAuthentication yes(把这个注释掉,也就是关闭)
UseDNS no (改成no)

以守护进程(socket)的方式传输数据

rsync 命令使用用法

rsync -参数 用户名@同步服务器的IP::rsyncd.conf中那个方括号里的内容(配置文件中的模块名) 本地存放路径。

rsync -avzP [email protected]::nemo /backup

服务器端的配置过程

安装rysnc

yum -y install rsync xinetd

vi /etc/xinetd.d/rsync

将yes 修改为no IPV6修改为IPV4

1、查看rsync安装包

[root@backup ~]# rpm -qa rsync

2、添加rsync服务的用户,管理本地目录

[root@backup ~]# useradd rsync -s /sbin/nologin -M
[root@backup ~]# tail -1 /etc/passwd
rsync:x:501:501::/home/rsync:/sbin/nologin

3、生成rsyncd.conf配置文件

查看 rsyncd.conf

[root@backup backup]# cat /etc/rsyncd.conf 
config_______________start
#15:01 2007-6-5
#rsyncd.conf start##
uid = rsync
gid = rsync
use chroot = no
max connections = 200
timeout = 300
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
[backup]
path = /backup
ignore errors
read only = false
list = false
hosts allow = 172.16.1.0/24
hosts deny = 0.0.0.0/32
auth users = rsync_backup
secrets file = /etc/rsync.password
#rsync_config____________end

配置rsyncd.conf

[root@backup ~]# vim /etc/rsyncd.conf 
#rsync_config_______________start
#15:01 2018-6-5
#rsyncd.conf start##
uid = rsync #用户远端的命令使用rsync访问共享目录
gid = rsync #用户组
use chroot = no #安全相关
max connections = 200 #最大连接数
timeout = 300 #超时时间(单位/秒)
pid file = /var/run/rsyncd.pid  #(进程号对应的进程号文件)
lock file = /var/run/rsync.lock #锁文件,防止文件不一致
log file = /var/log/rsyncd.log  #日志文件
[backup]  #模块名称
path = /backup  #服务器端提供访问的目录
ignore errors #忽略错误
read only = false #可写
list = false  #不让列表(相当于ls)
hosts allow = 172.16.1.0/24 #允许的网段
hosts deny = 0.0.0.0/32  #拒绝的网段
auth users = rsync_backup #连接的虚拟用户,非系统用户
secrets file = /etc/rsync.password #虚拟用户的账号密码文件
#rsync_config____________end

4、rsyncd.conf的auth users配置账户,远程连接

并根据secrets file参数生成密码文件

法一
echo "rsync_backup:cloudbility" >/etc/rsync.password
cat /etc/rsync.password

法二
[root@backup ~]# vim  /etc/rsync.password
rsync_backup:cloudbility

[root@backup ~]# cat /etc/rsync.password
rsync_backup:cloudbility

5、为密码文件配置权限

chmod 600 /etc/rsync.password
ls -l /etc/rsync.password

6、创建共享的目录并授权rsync服务管理

法一:
[root@backup ~]# mkdir /backup

[root@backup ~]# ls -ld /backup/
drwxr-xr-x 2 root root 4096 1月  16 20:08 /backup/
(如果不修改权限的话,远程访问过来是用rsync但是这个目录的属组和属主都收root 就无法把远方的数据推送过来,没有写权限。)

[root@backup ~]# chown rsync.rsync /backup/
(更改属组和属主)

[root@backup ~]# ls -ld /backup/
drwxr-xr-x 2 rsync rsync 4096 1月  16 20:08 /backup/

法二:
mkdir /backup -p
chown -R rsync.rsync /backup
如果没有/backup目录,就会chdir failed.(失败的)

7、启动rsync服务并检查

[root@backup ~]# rsync --daemon  
开启rsync服务

[root@backup ~]# ps -ef|grep rsync|grep -v grep
root       5116   5100  0 19:14 pts/0    00:00:00 vim /etc/rsyncd.conf
root       5193      1  0 20:05 ?        00:00:00 rsync --daemon
(为什么是root在运行呢?因为远程访问的用户才会使用rsync来使用,上面配置文件有写)

查看运行端口
[root@backup ~]# lsof -i :873
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
rsync   5193 root    3u  IPv4  19935      0t0  TCP *:rsync (LISTEN)
rsync   5193 root    5u  IPv6  19936      0t0  TCP *:rsync (LISTEN)

[root@backup ~]# netstat -lntup|grep 873
tcp        0      0 0.0.0.0:873                 0.0.0.0:*                   LISTEN      5193/rsync          
tcp        0      0 :::873                      :::*                        LISTEN      5193/rsync

8、加入开机自启动

[root@backup ~]# echo "/usr/bin/rsync --damon" >>/etc/rc.local

[root@backup ~]# tail -1 /etc/rc.local
/usr/bin/rsync --damon

排错过程

  1. 输出结果

  2. 日志 tail /var/log/rsyncd.log

  3. 熟练部署过程(原理)

rsync客户端操作方法

1、生成连接服务器的密码文件

法一:
echo "cloudbility" >/etc/rsync.password

法二:
[root@nfs01 ~]# vim /etc/rsync.password

[root@nfs01 ~]# cat /etc/rsync.password
cloudbility

2、为密码文件配置权限

[root@nfs01 ~]# chmod 600 /etc/rsync.password

[root@nfs01 ~]# ll /etc/rsync.password
-rw------- 1 root root 7 1月  16 20:58 /etc/rsync.password

3、同步文件

创建样本

[root@nfs01 ~]# mkdir /backup -p

[root@nfs01 ~]# cd /backup/


[root@nfs01 backup]# touch stu{01..100}

[root@nfs01 backup]# ls
stu001  stu010  stu02   stu029  stu038  stu047  stu056  stu065  stu074  stu083  stu092
stu002  stu011  stu020  stu03   stu039  stu048  stu057  stu066  stu075  stu084  stu093

推送到backup server:

法一:需要密码
[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/(模块名)

法二:无需密码
[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/(模块名) --password-file=/etc/rsync.password

法三:无需密码
[root@nfs01 backup]# rsync -avz /backup/ rsync://[email protected]/backup/(模块名) --password-file=/etc/rsync.password

从backup server拉取/backup下的文件到本地/backup下。

法一:需要密码
[root@nfs01 backup]# rsync -avz [email protected]::backup(模块名) /backup/ 

法二:免密
[root@nfs01 backup]# rsync -avz [email protected]::backup(模块名) /backup/ --password-file=/etc/rsync.password  

法三:免密
[root@nfs01 backup]# rsync -avz rsync://[email protected]/backup/(模块名) /backup/ --password-file=/etc/rsync.password

提示上述的backup为模块名,不是路径

增加模块

[root@backup backup]# vim /etc/rsyncd.conf
#15:01 2018-6-5
#rsyncd.conf start##
uid = rsync
gid = rsync
use chroot = no
max connections = 200
timeout = 300
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock
log file = /var/log/rsyncd.log
ignore errors
read only = false
list = false
hosts allow = 172.16.1.0/24
hosts deny = 0.0.0.0/32
auth users = rsync_backup
secrets file = /etc/rsync.password
[backup]
path = /backup
[cloudbility]
path = /cloudbility
##rsync_config____________end

排除同步:

排除推送

排除单个文件:

--exclude=a  (排除a)

[root@nfs01 backup]# rsync -avz --exclude=a /backup/ [email protected]::backup/ --password-file=/etc/rsync.password
sending incremental file list
./bcdefg

排除多个文件:

1)
排除a 和b 
[root@nfs01 backup]# rsync -avz --exclude={a,b} /backup/ [email protected]::backup/ --password-file=/etc/rsync.password
sending incremental file list
./cdefg

2)
排除连续的a-f
[root@nfs01 backup]# rsync -avz --exclude={a..f} /backup/ [email protected]::backup/ --password-file=/etc/rsync.password
sending incremental file list
./g

sent 75 bytes  received 30 bytes  210.00 bytes/sec
total size is 0  speedup is 0.00

1)拉取和推送都可以排除。

2)也可以服务端排除,配置文件里参数。

3)exclude=a b c d

完全同步:无差异同步–delete

[root@nfs01 backup]# rsync -avz --delete /backup/ [email protected]::backup/ --password-file=/etc/rsync.password
sending incremental file list

abcdef

rsync三种工作模式

1)local(本地模式):(cd,rm)

2)通道模式:
 rsync -avzP -e 'ssh -p 22' /etc [email protected]:/tmp/
 一般配合ssh key免密钥传输,结合定时任务。

 3)daemon模式
内网不需要加密,加密性能有损失。

如果要外网的话使用vpn(PPTP。openVPN,ipsec)

rsync服务模式故障常见问题解答

1)小 BUG

[root@backup backup]# vim /etc/rsyncd.conf
#hosts deny = 0.0.0.0/32
把 hosts deny(拒绝的ip段)注释掉,因为当

hosts allow = 172.16.1.0/24
#hosts deny = 0.0.0.0/32
这两个在一起的时候,发现10段的ip 也能把数据推送到backup server。所以必须注释掉
hosts deny。

提示:更改配置文件之后要重启服务,因为每次Linux都是把配置文件放到内存。
先杀死进程,然后检查
[root@backup backup]# pkill rsync
[root@backup backup]# lsof -i :873

重启再检查看看
[root@backup backup]# rsync --daemon
[root@backup backup]# lsof -i :873
COMMAND  PID USER   FD   TYPE DEVICE SIZE/OFF NODE NAME
rsync   7718 root    4u  IPv4  33811      0t0  TCP *:rsync (LISTEN)
rsync   7718 root    5u  IPv6  33812      0t0  TCP *:rsync (LISTEN)

2)服务端没有这个目录

提示报错信息

[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/ --password-file=/etc/rsync.password 
@ERROR: chdir failed


解决方法:
服务端创建目录
[root@backup backup]# mkdir /backup
[root@backup backup]# ll -d /backup/
drwxr-xr-x 2 root root 4096 Jan 17 15:52 /backup/

[root@backup backup]# chown -R rsync.rsync /backup/ 
(/etc/rsyncd.conf配置文件里的uid和gid)

3)权限不够

提示报错信息

[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/ --password-file=/etc/rsync.password 
sending incremental file list
./
rsync: failed to set times on "." (in backup): Operation not permitted (1)
stu1
stu10
stu2
stu3
stu4
stu5
stu6
stu7
stu8
stu9
rsync: mkstemp ".stu1.oraZ3Y" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu10.n1jKm7" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu2.dLFwFf" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu3.LKKjYn" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu4.nSI7gw" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu5.p4CWzE" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu6.HE5OSM" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu7.jGRIbV" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu8.p4cDu3" (in backup) failed: Permission denied (13)
rsync: mkstemp ".stu9.EZbyNb" (in backup) failed: Permission denied (13)

sent 467 bytes  received 201 bytes  1336.00 bytes/sec
total size is 0  speedup is 0.00
rsync error: some files/attrs were not transferred (see previous errors) (code 23) at main.c(1039) [sender=3.0.6]

解决方法
[root@backup backup]# ll -d /backup/
drwxr-xr-x 2 root root 4096 Jan 17 15:52 /backup/

[root@backup backup]# chown -R rsync.rsync /backup/ 
(/etc/rsyncd.conf配置文件里的uid和gid)

4)没有创建uid

提示错误信息

[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/ --password-file=/etc/rsync.password 
@ERROR: invalid uid rsync


解决方法:
[root@backup backup]# useradd rsync -s /sbin/nologin -M

5)客户端/etc/rsync.password 配置文件里的密码错误(注意空格)

[root@nfs01 backup]# rsync -avz /backup/ [email protected]::backup/ --password-file=/etc/rsync.password 
@ERROR: auth failed on module backup

解决:
查看服务端的日志配置文件的报错信息。
[root@backup backup]# cat /var/log/rsyncd.log  
2017/01/17 16:04:36 [7813] auth failed on module backup from unknown (172.16.1.31): password mismatch

提示我们密码错误:
查看服务器端的配置文件和密码,然后,再看客户端的。
[root@backup backup]# vim /etc/rsync.password 
rsync_backup:cloudbility

6)连接被拒绝

提示信息

[root@nfs01 backup]# rsync -avz /backup/ [email protected]::cloudbility/
rsync: failed to connect to 172.16.1.41: Connection refused (111)

解决,
1)服务端防火墙是否关闭iptables

2)873端口是否开放。
重启rsync服务。
[root@backup cloudbility]# rsync --daemon
[root@backup cloudbility]# lsof -i :873

rsync守护进程(daemon)服务传输数据排错思路:

rsync服务端排错思路

1)查看rsync服务配置文件路径是否正确,正确的默认路径为:/etc/rsyncd.conf

2)查看配置文件里的host allow.host deny允许的网段是否允许客户端访问的IP网段。

3)查看配置文件中path参数里的路径是否存在,权限是否正确(正常应为位置文件中的UID参数对应的属主和组)

4)查看rsync服务是否启动,查看命令为:ps -ef|grep rsync. 端口是否存在 netstat -lnt|grep 873.

5)查看iptables防火墙和SELinux是否开启允许rsync服务通过,也可以考虑关闭。

6)查看服务端rsync配置的密码文件权限是否是600;密码文件格式是否正确。 正确格式为 用户名:密码 。文件路径和配置文件里的secrect files参数对应。

7)如果是推送数据,要查看下,配置rsyncd.conf文件中用户是否对模块下的目录有可读写权限

rsync客户端排除思路

1)查看客户端rsync配置的密码文件是否为600权限,密码文件格式是否正确。
注意,仅西药有密码,并且和服务端的密码一致。

2)用telnet连接rsync服务器IP地址873端口,查看服务是否启动
(可测试服务端防火墙是都阻挡)。 telnet 10.0.0.41 873

3)客户端执行命令时rsync -avzP [email protected]::cloudbility/test/test --password-file=/etc/rsync.password
此命令的细节要记清楚,尤其是10.0.0.41::cloudbility/test/处的双冒号及随其后的cloudbility
的模块名称;

rsync优缺点:

rsync优点:

1)增量备份,支持socket(daemon守护进程),集中备份(支持推拉,都是以客户端为参照物);

2)远程SEHLL通道模式还可以加密(SSH)传输,socket(daemon守护进程)需要加密传输,
可以利用VPN服务或ipsec服务;

rsync缺点:

1)大量小文件同步的时候,比对时间较长,有的时候,rsync进程可能会停止。

2)同步大文件,10G这样的大文件有时也会出现问题,中断。未完整同步之前,是隐藏文件.
可以通过续传等参数实现传输,

一次性远程拷贝可以用scp;

(完)

rsync的小坑——请绕过

今天磁盘满了,打算将占磁盘大的文件给移走,再采用软连接的。同步的时候出现了一点小问题。

第一天:

先将要同步的文件给同步了一遍。

执行命令

rsync -auv /data/mysql/game /data1/mysql
rsync -auv /data/mysql/integral /data1/mysql
rsync -auv /data/mysql/interact /data1/mysql
rsync -auv /data/mysql/match /data1/mysql
rsync -auv /data/mysql/sns_admin /data1/mysql
rsync -auv /data/mysql/stock /data1/mysq

第二天:

又同步了一遍

rsync -auv /data/mysql/game /data1/mysql/game
rsync -auv /data/mysql/integral /data1/mysql/integral
rsync -auv /data/mysql/interact /data1/mysql/interact
rsync -auv /data/mysql/match /data1/mysql/match
rsync -auv /data/mysql/sns_admin /data1/mysql/sns_admin 
rsync -auv /data/mysql/stock /data1/mysql/stock

快要同步完的时候,检查文件大小,发现文件大了一倍。

原来第二步命令将/data/mysql/game文件 放在/data1/mysql/game文件下了。

这也不算是rsync的坑吧

应该这样这行

rsync -auv /data/mysql/game/ /data1/mysql/game/
rsync -auv /data/mysql/integral/ /data1/mysql/integral/
rsync -auv /data/mysql/interact/ /data1/mysql/interact/
rsync -auv /data/mysql/match/ /data1/mysql/match/
rsync -auv /data/mysql/sns_admin/ /data1/mysql/sns_admin/ 
rsync -auv /data/mysql/stock/ /data1/mysql/stock/

或者执行和昨天一样的命令

            rsync -auv /data/mysql/game         /data1/mysql
            rsync -auv /data/mysql/integral    /data1/mysql
            rsync -auv /data/mysql/interact     /data1/mysql
            rsync -auv /data/mysql/match        /data1/mysql
            rsync -auv /data/mysql/sns_admin    /data1/mysql
            rsync -auv /data/mysql/stock        /data1/mysq 

就可以了。

小结:

1、使用rsync同步,只要之前同步的内容和现在同步的内容有一点改变,就会重新全量同步,因此,同步的时候尽量找长时间没有变化的大文件
2、rsync不会追加文件

rsync+inotify实现实时同步案例

公司网站因负载过高不得不搞个负载均衡,那么问题来了,每次更新网站,负载均衡下的服务器全部需要更新,当数据量过大的时候会很麻烦,并切效率低下,当时考虑到用rsync去实时同步,写个计划任务,但更新数据很频繁,并且rsync不能实时的去监测、同步数据,虽然它可以通过linux守护进程的方式进行触发同步,但是两次触发动作一定会有时间差,这样就导致了服务端和客户端数据可能出现不一致,无法在应用故障时完全的恢复数据。基于以上原因,rsync+inotify出现了!

inotify介绍

inotify是一种强大的、细粒度的、异步的文件系统事件控制机制。linux内核从2.6.13起,加入了inotify支持,通过inotify可以监控文件系统中添加、删除、修改、移动等各种事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools正是实施监控的软件。

rsync+inotify同步逻辑图
未分类

环境部署

主机名                主机IP地址            系统版本                系统内核版本
inotify-master    192.168.1.1    CentOS release 6.4 (Final)    2.6.32-358.el6.x86_64
inotify-slave    192.168.1.2    CentOS release 6.4 (Final)    2.6.32-358.el6.x86_64

inotify-slave部署

部署rsync服务,rsync daemon工作模式。

检查是否安装rsync

[root@inotify-slave ~]# rpm -aq rsync
rsync-3.0.6-9.el6.x86_64

新建rsync用户及模块目录并更改其用户组

[root@inotify-slave mail]# useradd rsync -s /sbin/nologin  -M #添加rsync用户
[root@inotify-slave mail]# grep rsync /etc/passwd
rsync:x:2004:2004::/home/rsync:/sbin/nologin
[root@inotify-slave mail]# mkdir /backup   #创建rsync daemon工作模式的模块目录
[root@inotify-slave mail]# ll -d /backup/
drwxr-xr-x. 2 root root 4096 4月  22 14:13 /backup/
[root@inotify-slave mail]# chown rsync.rsync /backup/   #更改模块目录的用户组
[root@inotify-slave mail]# ll -d /backup/
drwxr-xr-x. 2 rsync rsync 4096 4月  22 14:13 /backup/

编写rsync daemon配置文件/etc/rsyncd.conf

[root@inotify-slave /]# cat /etc/rsyncd.conf
##rsyncd.conf start##
#工作中指定用户(需要指定用户)
uid = rsync
gid = rsync
#相当于黑洞.出错定位
use chroot = no
#有多少个客户端同时传文件
max connections = 200
#超时时间
timeout = 300
#进程号文件
pid file = /var/run/rsyncd.pid
#日志文件
lock file = /var/run/rsync.lock
#日志文件
log file = /var/log/rsyncd.log
#模块开始
#这个模块对应的是推送目录
#模块名称随便起
[backup]
#需要同步的目录
path = /backup/
#表示出现错误忽略错误
ignore errors
#表示网络权限可写(本地控制真正可写)
read only = false
#这里设置IP或让不让同步
list = false
#指定允许的网段
hosts allow = 192.168.1.0/24
#拒绝链接的地址,一下表示没有拒绝的链接。
hosts deny = 0.0.0.0/32
#不要动的东西(默认情况)
#虚拟用户
auth users = rsync_backup
#虚拟用户的密码文件
secrets file = /etc/rsync.password
#配置文件的结尾
#rsync_config_______________end

配置虚拟用户的密码文件

[root@inotify-slave /]# echo "rsync_backup:leesir" >/etc/rsync.password
[root@inotify-slave /]# cat /etc/rsync.password
rsync_backup:leesir   #注:rsync_backup为虚拟用户,leesir为这个虚拟用户的密码
[root@inotify-slave /]# chmod 600 /etc/rsync.password #为密码文件提权,增加安全性
[root@inotify-slave /]# ll /etc/rsync.password
-rw-------. 1 root root 20 4月  22 14:20 /etc/rsync.password

启动rsync 服务

[root@inotify-slave /]# rsync --daemon   #启动rsync服务
[root@inotify-slave /]# ps -ef |grep rsync
root     14871     1  0 14:24 ?        00:00:00 rsync --daemon
root     14873 14788  0 14:24 pts/0    00:00:00 grep rsync
[root@inotify-slave /]# netstat -lnutp |grep rsync
tcp        0      0 0.0.0.0:873                 0.0.0.0:*                   LISTEN      14871/rsync
tcp        0      0 :::873                      :::*                        LISTEN          14871/rsync

通过inotify-master测试推送

inotify-master配置密码文件,测试推送
[root@inotify-master ~]# echo "leesir" >/etc/rsync.password
[root@inotify-master ~]# cat /etc/rsync.password
leesir   #注意:这里只要写密码即可,切记。
[root@inotify-master ~]# chmod 600 /etc/rsync.password
[root@inotify-master ~]# ll /etc/rsync.password
-rw------- 1 root root 7 4月  22 14:32 /etc/rsync.password
[root@inotify-master ~]# echo "hello leesir">test.txt
[root@inotify-master ~]# cat test.txt
hello leesir
[root@inotify-master ~]# rsync -avz test.txt [email protected]::backup --password-file=/etc/rsync.password
sending incremental file list
test.txt
sent 82 bytes  received 27 bytes  72.67 bytes/sec
total size is 13  speedup is 0.12
inotify-slave检查:
[root@inotify-slave /]# ll /backup/
总用量 4
-rw-r--r--. 1 rsync rsync 13 4月  22 14:34 test.txt
[root@inotify-slave /]# cat /backup/test.txt
hello leesir

inotify-master部署

注: inotify是rsync客户端安装和执行的 企业场景压力测试200-300个同步限制,受网卡,磁盘,带宽等的制约。

查看当前系统是否支持inotify

[root@inotify-master ~]# ll /proc/sys/fs/inotify/
总用量 0
-rw-r--r-- 1 root root 0 4月  22 14:56 max_queued_events
-rw-r--r-- 1 root root 0 4月  22 14:56 max_user_instances
-rw-r--r-- 1 root root 0 4月  22 14:56 max_user_watches
#显示这三个文件则证明支持。

拓展:

/proc/sys/fs/inotify/max_queued_evnets      
表示调用inotify_init时分配给inotify instance中可排队的event的数目的最大值,超出这个值的事件被丢弃,但会触发IN_Q_OVERFLOW事件。
/proc/sys/fs/inotify/max_user_instances 
表示每一个real user ID可创建的inotify instatnces的数量上限。
/proc/sys/fs/inotify/max_user_watches 
表示每个inotify instatnces可监控的最大目录数量。如果监控的文件数目巨大,需要根据情况,适当增加此值的大小。
例如: echo 30000000 > /proc/sys/fs/inotify/max_user_watches

下载inotify源码包并编译安装

root@inotify-master tools]# wget http://github.com/downloads/rvoicilas/inotify-tools/inotify-tools-3.14.tar.gz  #下载inotify源码包
..................................
root@inotify-master tools]# ll inotify-tools-3.14.tar.gz
-rw-r--r-- 1 root root 358772 3月  14 2010 inotify-tools-3.14.tar.gz
[root@inotify-master tools]# tar zxf inotify-tools-3.14.tar.gz
[root@inotify-master tools]# cd inotify-tools-3.14
[root@inotify-master inotify-tools-3.14]# ./configure --prefix=/usr/local/inotify-3.14 #配置inotify,并指定安装路径为/usr/local/inotify-3.14
................................
[root@inotify-master inotify-tools-3.14]# make && make install
................................

inotify之inotifywait命令常用参数详解

[root@inotify-master inotify-tools-3.14]# cd /usr/local/inotify-3.14/
[root@inotify-master inotify-3.14]# ./bin/inotifywait --help
-r|--recursive   Watch directories recursively. #递归查询目录
-q|--quiet      Print less (only print events). #打印监控事件的信息
-m|--monitor   Keep listening for events forever.  Without this option, inotifywait will exit after one  event is received.        #始终保持事件监听状态
--excludei <pattern>  Like --exclude but case insensitive.    #排除文件或目录时,不区分大小写。
--timefmt <fmt> strftime-compatible format string for use with %T in --format string. #指定时间输出的格式
--format <fmt>  Print using a specified printf-like format string; read the man page for more details.
#打印使用指定的输出类似格式字符串
-e|--event <event1> [ -e|--event <event2> ... ] Listen for specific event(s).  If omitted, all events are  listened for.   #通过此参数可以指定需要监控的事件,如下所示:
Events:
access           file or directory contents were read       #文件或目录被读取。
modify           file or directory contents were written    #文件或目录内容被修改。
attrib            file or directory attributes changed      #文件或目录属性被改变。
close            file or directory closed, regardless of read/write mode    #文件或目录封闭,无论读/写模式。
open            file or directory opened                    #文件或目录被打开。
moved_to        file or directory moved to watched directory    #文件或目录被移动至另外一个目录。
move            file or directory moved to or from watched directory    #文件或目录被移动另一个目录或从另一个目录移动至当前目录。
create           file or directory created within watched directory     #文件或目录被创建在当前目录
delete           file or directory deleted within watched directory     #文件或目录被删除
unmount         file system containing file or directory unmounted  #文件系统被卸载

编写监控脚本并加载到后台执行

[root@inotify-master scripts]# cat inotify.sh
#!/bin/bash
#para
host01=192.168.1.160  #inotify-slave的ip地址
src=/backup/        #本地监控的目录
dst=backup         #inotify-slave的rsync服务的模块名
user=rsync_backup      #inotify-slave的rsync服务的虚拟用户
rsync_passfile=/etc/rsync.password   #本地调用rsync服务的密码文件
inotify_home=/usr/local/inotify-3.14    #inotify的安装目录
#judge
if [ ! -e "$src" ] 
|| [ ! -e "${rsync_passfile}" ] 
|| [ ! -e "${inotify_home}/bin/inotifywait" ] 
|| [ ! -e "/usr/bin/rsync" ];
then
echo "Check File and Folder"
exit 9
fi
${inotify_home}/bin/inotifywait -mrq --timefmt '%d/%m/%y %H:%M' --format '%T %w%f' -e close_write,delete,create,attrib $src 
| while read file
do
#  rsync -avzP --delete --timeout=100 --password-file=${rsync_passfile} $src $user@$host01::$dst >/dev/null 2>&1
cd $src && rsync -aruz -R --delete ./  --timeout=100 $user@$host01::$dst --password-file=${rsync_passfile} >/dev/null 2>&1
done
exit 0
[root@inotify-master scripts]# sh inotify.sh &  #将脚本加入后台执行
[1] 13438
[root@inotify-master scripts]#

实时同步测试

inotify-master操作:

[root@inotify-master scripts]# cd /backup/
[root@inotify-master backup]# ll
总用量 0
[root@inotify-master backup]# for a in `seq 200`;do touch $a;done  #创建200个文件
[root@inotify-master backup]# ll  --time-style=full-iso
总用量 0
-rw-r--r-- 1 root root 0 2014-04-22 15:34:08.141497569 +0800 1
-rw-r--r-- 1 root root 0 2014-04-22 15:34:08.172497529 +0800 10
-rw-r--r-- 1 root root 0 2014-04-22 15:34:08.235497529 +0800 100
-rw-r--r-- 1 root root 0 2014-04-22 15:34:08.236497529 +0800 101
-rw-r--r-- 1 root root 0 2014-04-22 15:34:08.237497529 +0800 102
...................................

inotify-slave检查

[root@inotify-slave backup]# ll  --time-style=full-iso
总用量 0
-rw-r--r--. 1 rsync rsync 0 2014-04-22 15:34:08.393823754 +0800 1
-rw-r--r--. 1 rsync rsync 0 2014-04-22 15:34:08.393823754 +0800 10
-rw-r--r--. 1 rsync rsync 0 2014-04-22 15:34:08.393823754 +0800 100
-rw-r--r--. 1 rsync rsync 0 2014-04-22 15:34:08.393823754 +0800 101
-rw-r--r--. 1 rsync rsync 0 2014-04-22 15:34:08.393823754 +0800 102
..........................

使用inotify-tools与rsync构建实时备份系统

使用inotifywait监控文件变动

inotifywait是 inotify-tools 包中提供的一个工具,它使用 inotify API 来监控文件/目录中的变动情况。

在archlinux上,我们可以使用下面命令来安装

sudo pacman -S --noconfirm inotify-tools

平时 inotifywait 会挂起在那里,直到文件/目录发生了要引起关注的事件后,它会退出并输出事件发生的场所、事件的名称以及引起事件的文件(当事件发生在目录上时才会输出).

inotifywait 最常用的选项有两个,一个是 -r 一个是 -e ,其中:

-r
表示递归监控子目录中文件发生的事件

-e
指定要监控的事件列表。对于备份系统来说,只需要监控 modify、create和delete三种事件就行了。

比如,我们运行

inotifywait -r -e modify,create,delete /tmp

表示监控 /tmp 目录及其子目录中文件修改、文件创建和文件删除三种事件。

这时程序一直在挂起状态

[lujun9972@X61 ~]$ inotifywait -r -e modify,create,delete /tmp
Setting up watches.  Beware: since -r was given, this may take a while!
Watches established.

这时在 /tmp 目录下新建一个文件

touch /tmp/newFile

则 inotifywait 进程退出,并输出如下信息

/tmp/ CREATE newFile

使用rsync同步变动

rsync是一款快速增量备份工具。它的具有以下几个特点使得它很适合用作做备份的工具:

  • 增量备份,只会传输修改过的内容
  • 可以在传输过程中实时解压缩,减少带宽消耗
  • 可以保持原来文件的权限、事件、软硬链接
  • 即支持本机复制,也支持远程复制

rsync常用法为:

rsync -avz --delete  src/ foo:/data

其中

-a
表示archive mode,即备份目录下的所有内容(包括子目录中的内容),并且保持软链接、文件属性、文件修改事件、文件的所有者和宿主信息不变,并且同步字符/块设备以及命名socket和fifo等特殊文件。

-v
表示输出备份的详细信息

-z
表示传输时进行压缩

--delete
删除备份目的地里src中没有的文件

src/
表示要备份的是src目录下的所有内容,注意这里最后的 / 不能去掉,否则会把src目录本身备份过去

foo:/data
表示备份的目的地是foo主机下的 /data/ 目录

整合起来

接下来我们只需要用个 while 死循环把两个工具整合起来就行了,非常简单

#!/bin/bash

if [[ $# -ne 2 ]];then
    cat<<EOF
Usage $(basename $0) source_dir [host:]dest_dir
EOF
    exit 0
fi

source_dir=$1
dest_dir=$2
while :
do
    inotifywait -r -e modify,create,delete ${source_dir} && rsync -avz ${source_dir}/ ${dest_dir} --delete
done

这里有必要说明的是,虽然用 inotifywait 能探测出文件具体做了什么改动,但实际上我们根本不需要知道具体的改变是什么。

我们只需要知道有所改变了,然后具体改变了什么由 rsync 来自己处理就行了。

使用rsync定时远程同步

一般场景下,通过rsync可以结合crontab实现按时自动备份,在远程自动同步的场景下,rsync 需要以守护进程的方式来运行,本文记录实现异地自动备份的过程。

生产服务器主机A的地址:192.168.214.190 :centos7.4

备份数据主机B的地址:192.168.214.187 :centos6.9

客户端和服务端都要安装rsync,安装完后有些系统不会生成rsyncd.conf,需要自己创建在 /etc/rsync.d/rsyncd.conf

【在centos7.4上安装rsync会默认生成/etc/rsyncd.conf文件,但是在centos6.9上安装后则不会生成,并且,如果在要自己定义文件位置,以守护进程方式启动,那么任然要在/etc/下新建一个rsyncd.conf的文件,否则无法启动。】

服务端安装rsync:

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

创建配置文件

[root@yufu ~]# mkdir -p /etc/rsync.d
[root@yufu ~]# touch /etc/rsync.d/rsyncd.conf
[root@yufu ~]# chmod 600 /etc/rsync.d/rsync.conf

编辑配置文件内容

vim /etc/rsync.d/rsyncd.conf

log file = /var/log/rsyncd.log
pid file = /var/run/rsyncd.pid
lock file = /var/run/rsync.lock

[bak]
path=/opt/server
uid = root
gid = root
ignore = errors
read only = no
write only = no
host allow = *
max connections = 5
host deny = 192.168.22.21
list = false
auth users = feng
secrets file = /etc/rsync.d/server.pass

添加备份用户的用户密码文件,并修改文件权限

echo 'filebak:filebak' > /etc/rsync.d/server.pass
chmod 600 server.pass

服务端的rsync安装配置好后就可启动了,rsync是以守护进程的方式启动:

[root@localhost ~]#rsync --daemon --config=/etc/rsync.d/rsyncd.conf 

[root@localhost ~]#ps -ef | grep rsync
root      2356     1  0 17:29 ?        00:00:00 rsync --daemon --config=/etc/rsync.d/rsyncd.conf
root      2361  1965  0 17:29 pts/1    00:00:00 grep --color=auto rsync

到此服务端的的设置完成,接着安装客户端,在备份主机上不用做任何设置,只要安装rsync服务和设置crontab任务计划就可以, 为了在同步的过程中不用输入密码,因此需要在备份主机上创建一个secrets 文件,该文件内容是服务端的rsyncd.conf中“auth users”指定的用户的密码;这个文件名和路径随意指定,只要在执行同步指令时指定即可。

安装rsync

yum install rsync -y

向客户端添加同步用户的密码

[root@yufu ~]# echo 'fsz...' > /etc/rsync.d/feng.pass

[root@yufu ~]# chmod 600 /etc/rsync.d/feng.pass 

在客户端执行同步

[root@yufu ~]# rsync -arzvtopg --delete [email protected]::bak /opt/app/ --password-file=/etc/rsync.d/feng.pass 
rsync: failed to connect to 192.168.214.190: No route to host (113)
rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.6]

执行报错:原因是服务端的防火墙没有放行策略,关闭防火墙;

[root@localhost ~]#systemctl stop firewalld

再执行:

[root@yufu ~]# rsync -arzvtopg --delete [email protected]::bak /opt/app/ --password-file=/etc/rsync.d/feng.pass 
receiving incremental file list
./
install-lnmp.sh

sent 75 bytes  received 1410 bytes  990.00 bytes/sec
total size is 3522  speedup is 2.37
[root@yufu ~]# cd /opt/app/ && tree
.
└── install-lnmp.sh

0 directories, 1 file
[root@yufu app]# ls
install-lnmp.sh

客户端设置定时备份:添加crontab任务计划,每天定时同步文件

[root@yufu ~]# crontab -l
*/1 * * * * /usr/bin/rsync -arzvtopg --delete [email protected]::bak /opt/app/ --password-file=/etc/rsync.d/feng.pass
设置定时同步,作为测试,设置每分钟同步一次

服务端测试文件更新脚本

#!/bin/bash
dir=/opt/server
cd $dir
for i in $(seq 1 10)
do
touch file$i
sleep 61
done

测试脚本执行结束后再查看服务端和客户端的目录情况

[root@yufu app]# ls   #客户端
file1  file10  file2  file3  file4  file5  file6  file7  file8  file9  install-lnmp.sh  tess


[root@localhost server]#ls  #服务端
file1  file10  file2  file3  file4  file5  file6  file7  file8  file9  install-lnmp.sh  tess

rsync+lsyncd实现文件实时同步

可参考http://seanlook.com/2015/05/06/lsyncd-synchronize-realtime/
可参考http://openlinuxfly.blog.51cto.com/7120723/1679279
可参考http://segmentfault.com/a/1190000002737213

一、环境

lsyncd    192.168.3.71

rsync     192.168.3.72

二、配置rsync服务器

配置rsync以xinetd方式运行

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

#修改/etc/xinetd.d/rsync
[root@rsync ~]# vim /etc/xinetd.d/rsync
service rsync
{
    disable         = no          ##将yes改成no  
    socket_type     = stream
    wait            = no
    user            = root
    server          = /usr/bin/rsync
    server_args     = --daemon
    log_on_failure  += USERID
}

#启动xinetd服务
[root@rsync ~]# service xinetd start
Starting xinetd:                                           [  OK  ]

#rsync默认的监听端口是873,查看873号端口是否启动
[root@rsync ~]# netstat -tunlp
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name   
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      1247/sshd           
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      1324/master         
tcp        0      0 :::22                       :::*                        LISTEN      1247/sshd           
tcp        0      0 ::1:25                      :::*                        LISTEN      1324/master         
tcp        0      0 :::873                      :::*                        LISTEN      1561/xinetd

创建rsync服务目录和配置文件

#创建rsync服务目录
[root@rsync ~]# mkdir /etc/rsyncd

# 创建配置文件
[root@rsync ~]# touch /etc/rsyncd/rsyncd.conf

# 创建密码文件
[root@rsync ~]# touch /etc/rsyncd/rsyncd.secrets

#权限修改
[root@rsync ~]# chown root:root /etc/rsyncd/rsyncd.secrets
[root@rsync ~]# chmod 600 /etc/rsyncd/rsyncd.secrets            #这里的权限设置必须是600

创建用户和密码

[root@rsync ~]# echo "rsync:test" >>/etc/rsyncd/rsyncd.secrets

创建rsync配置文件

[root@rsync ~]# cat /etc/rsyncd/rsyncd.conf 
# GLOBAL OPTIONS
uid = root
gid = root

use chroot = yes        #这个参数要设置成yes,如果同步的是软连接文件,同步过来后会多一个前缀,导致软连接不能正常使用

read only = no        #我们需要实时同步lsyncd服务器上的资源,这个需要有写权限,或者在模块中赋予写权限

#limit access to private LANs
hosts allow=192.168.3.0/255.255.0.0
hosts deny=*
max connections = 5

pid file = /var/run/rsyncd.pid

secrets file = /etc/rsyncd/rsyncd.secrets
#lock file = /var/run/rsync.lock           

motd file = /etc/rsyncd/rsyncd.motd        

#This will give you a separate log file
log file = /var/log/rsync.log               

#This will log every file transferred - up to 85,000+ per user, per sync
transfer logging = yes

log format = %t %a %m %f %b
syslog facility = local3
timeout = 300

# MODULE OPTIONS
[test]
path = /data/test
list=yes
ignore errors
auth users = rsync            #客户端连接过来使用的用户是rsync
comment = welcome to rsync server

编辑xinetd的rsync配置文件,添加配置文件路径

#添加rsync的配置文件路径
[root@rsync ~]# vim /etc/xinetd.d/rsync
service rsync
{
    disable = no
    socket_type     = stream
    wait            = no
    user            = root
    server          = /usr/bin/rsync
    server_args     = --daemon --config=/etc/rsyncd/rsyncd.conf    #添加配置文件路径
    log_on_failure  += USERID
}

#重启xinetd服务
[root@rsync ~]# service xinetd restart
Stopping xinetd:                                           [  OK  ]
Starting xinetd:                                           [  OK  ]
[root@rsync ~]# netstat -anpt |grep 873
tcp        0      0 :::873                      :::*                        LISTEN      1586/xinetd 

#创建数据目录
[root@rsync ~]# mkdir -p /data/test

三、配置lsyncd服务器

#安装rsync,lsyncd
[root@lsyncd ~]# rpm -ivh http://dl.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
[root@lsyncd ~]# sed -i 's@#b@b@g' /etc/yum.repos.d/epel.repo
[root@lsyncd ~]# sed  -i 's@mirrorlist@#mirrorlist@g' /etc/yum.repos.d/epel.repo
[root@lsyncd ~]# yum install rsync lsyncd -y

配置lsyncd服务配置文件

本地同步

1.1 本地目录同步:direct:cp/rm/mv。 适用:500+万文件,变动不大

[root@lsyncd ~]# vim /etc/lsyncd.conf 
settings {
        logfile         = "/tmp/lsyncd.log",
        statusFile      = "/tmp/lsyncd.status",
        statusInterval  = 5,
}

sync {
        default.direct,
        source          = "/data/test",            #要同步的源目录
        target          = "/data/dest",            #同步的目的目录
        delay           = 1,    
        maxProcesses    = 1,
}

#启动服务
[root@lsyncd ~]# /etc/init.d/lsyncd start
Starting lsyncd:                                           [  OK  ]

#测试,查看目录内容
[root@lsyncd ~]# ll /data/test
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:00 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:01 test.txt
[root@lsyncd ~]# ll /data/dest/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:00 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:01 test.txt

#创建一个新文件
[root@lsyncd ~]# touch /data/test/for.py

#查看结果
[root@lsyncd ~]# ll /data/dest/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:00 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:03 for.py
-rw-r--r-- 1 root root 0 Jul 30 15:01 test.txt

#删除/data/test目录下的txt文件
[root@lsyncd ~]# rm -rf /data/test/*.txt
[root@lsyncd ~]# ll /data/dest/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:03 for.py

1.2 本地目录同步rsync模式:rsync

#编辑lsyncd配置文件添加如下内容
[root@lsyncd ~]# vim /etc/lsyncd.conf 
sync{
        default.rsync,
        source          = "/data/test",
        target          = "/tmp/ceshi",            #如果目录不存在,会自动创建目录
        delete          = true,
        exclude         = { "test"},
        rsync = {
                compress = true,
                verbose  = true,
                archive  = true,
        }
}

#重启服务
[root@lsyncd ~]# /etc/init.d/lsyncd restart
Stopping lsyncd:                                           [  OK  ]
Starting lsyncd:                                           [  OK  ]

#测试
[root@lsyncd ~]# ll /tmp/ceshi/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:03 for.py

#在/data/test下添加一个文件ceshi.txt
[root@lsyncd ~]# touch /data/test/ceshi.txt
[root@lsyncd ~]# ll /tmp/ceshi/                #有点延迟,可能是虚拟机的原因
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:14 ceshi.txt
-rw-r--r-- 1 root root 0 Jul 30 15:03 for.py

远程同步

2.1 远程同步: rsync模式 + rsyncd daemon

#创建密码文件
[root@lsyncd ~]# echo "test" > /etc/backserver.pas
[root@lsyncd ~]# chmod 600 /etc/backserver.pas 

#修改lsyncd的配置文件,添加如下内容
[root@lsyncd ~]# vim /etc/lsyncd.conf 
sync{
        default.rsync,
        source          = "/data/test",
        target          = "[email protected]::test",    #这里的用户是192.168.3.72里设置的用户
        delete          = true,
        exclude         = { ".tmp"},
        delay           = 1,
        rsync   = {
                binary = "/usr/bin/rsync",
                archive = true,
                compress = true,
                verbose = true,
                password_file = "/etc/backserver.pas",    #需要的密码配置文件
                _extra  = {"--bwlimit=200",}
        }
}

[root@lsyncd ~]# /etc/init.d/lsyncd restart
Stopping lsyncd:                                           [  OK  ]
Starting lsyncd:                                           [  OK  ]

#测试,查看rsync:192.168.3.72上的test模块下的文件
[root@rsync ~]# hostname
rsync
[root@rsync ~]# ll /data/test/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:15 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:14 ceshi.txt
-rw-r--r-- 1 root root 0 Jul 30 15:03 for.py
-rw-r--r-- 1 root root 0 Jul 30 15:23 test

#在lsyncd上删除/data/test目录下的for.py
[root@lsyncd ~]# hostname 
lsyncd
[root@lsyncd ~]# rm -rf /data/test/for.py 

#查看结果
[root@rsync ~]# hostname
rsync
[root@rsync ~]# ll /data/test/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:15 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:14 ceshi.txt
-rw-r--r-- 1 root root 0 Jul 30 15:23 test

#测试添加一个文件
[root@lsyncd ~]# hostname
lsyncd
[root@lsyncd ~]# touch /data/test/docker.txt

#查看结果
[root@rsync ~]# ll /data/test/
total 0
-rw-r--r-- 1 root root 0 Jul 30 15:15 1.txt
-rw-r--r-- 1 root root 0 Jul 30 15:14 ceshi.txt
-rw-r--r-- 1 root root 0 Jul 30 15:31 docker.txt
-rw-r--r-- 1 root root 0 Jul 30 15:23 test

rsync远程同步

1、rsync:快速增量备份工具,实现远程同步,可使用ssh和rsync备份源rsync服务器:备份源,提供一个目录供客户端上传或下载

2、rsync的配置

建立rsync的配置文件:/etc/rsyncd.conf

use chroot=yes 禁锢在源地址

port 837 默认端口号为873

pid file 进程号文件位置

hosts allow 允许访问客户机地址

[wwwroot] 共享名

path=/路径 真正的文件夹位置

comment= 描述

read only=yes|no 只读|读写

auth users=用户名 认证的用户

secrets file=文件名路径 验证文件

验证文件格式: 用户名:密码

权限必须设置为600

3、管理rsync服务:

启动:rsync --daemon

停止:kill 进程号

4、rsync的使用

格式:rsync 选项 原始位置 目标位置

选项:-a:归档模式,等同于 -rlptgoD

  -r:递归,包含目录

  -p:权限(保留权限)

  -t:时间

  -z:压缩

  -v:同步过程信息

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

5、备份源(服务器端)的表达方式:

1)用户名@服务器IP::共享名

例:[email protected]::wwwroot

2)rsync://用户名@服务器IP/共享名

Rsync -avz [email protected]::wwwroot /root

6、实现免交互模式:

1)创建密码文件并设置权限为600

2)同步时使用 --password-file=文件名 的方式指定文件位置

7、实时同步:有变化则备份,无变化不备份

通过inotify机制实现,实时监控本地文件系统目录的变化,并作出通知响应,适当调整监控文件数量

inotify-tools辅助工具,有两个命令:

inotifywait:持续监控,实时输出结果

inotifywatch:短期监控,完成后输出结果

格式:inotifywait -mrq -e 监控事件类型 /监控目标

-m:持续监控 

-r:监控整个目录

-q:简化输出 

-e:监控事件类型

类型有:

modify(修改) 

create(创建) 

move(移动)

delete(删除) 

attrib(属性更改)

rsync备份同步文件

一、介绍

Rsync具有可使本地和远程两台主机之间的数据快速复制同步镜像、远程备份的功能。
cp,scp等工具拷贝均为完整的拷贝,而rsync除了可以完整拷贝外,还具有增量拷贝的功能。

官方文档:https://www.samba.org/ftp/rsync/rsync.html

二、常见应用场景

1) rsync+crontab 数据同步
2)实时数据同步rsync+inotify

三、工作模式(三种)

1)单个主机本地直接的数据传输

rsync -avz   /etc/hosts    /tmp        相当于cp
rsync -avz  --delete  /null/  /tmp/   相当于rm

2)remote shell

push:   rsync -avzP -e ' ssh -p 22'   /tmp/  [email protected] :/tmp/
pull :      rsync -avzP -e ' ssh -p  22'  [email protected] :/tmp/   /tmp/

3)rsync daemon

四、rsync 服务端配置

1)vi /etc/rsyncd.conf(需要手动生成)

uid = root  
gid = root   
user chroot = no   
max connections = 20   
timeout = 60  
pid file = /var/run/rsyncd.pid   
lock file = /var/run/rsyncd.lock  
motd file = /etc/rsyncd.motd     
log file = /var/log/rsyncd.log   
[backup]   
path = /backup   
ignore errors   
read only = no   
list = no   
hosts allow = 192.168.1.101  
auth users = rsync   
secrets file =/etc/rsyncd.pwd  

2)创建rsync用户及共享目录/backup

useradd rsync -s   /sbin/nologin -M
id  rsync
mkdir /backup
chown -R  rsync  /backup

3)创建密码文件

echo "rsync:123456">/etc/rsyncd.pwd
chmod 600  /etc/rsync.password

4)启动服务

/usr/bin/rsync  --deamon
netstat   -lntup |grep  rsync
ps  -ef |grep rsync |grep -v grep

5)加入开机自启动

echo "/usr/bin/rsync --deamon">>/etc/rc.local
cat  /etc/rc.local

五、rsync客户端配置

1、客户端不用配置,直接使用rsync命令就可以,

rsync -vzrtopg --progress --delete [email protected]::backup  /data/
rsync -vzrtopg --progress --delete /data/  [email protected]::backup

2、rsync无密码登陆,客户端需配置密码文件,只包含服务器端auth user的密码,不需要配置用户名 。

vim /etc/rsyncd.pwd 
123456
chmod 600  /etc/rsyncd.pwd

注:此处密码一定要与rsync服务器端密码文件中密码保持一致。

rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd [email protected]::backup /data/
rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd /data/ [email protected]::backup

3、rsync定时任务(备份本地目录/data/到服务端192.168.1.100)

crontab -e
0 1  * * *  rsync -vzrtopg --progress --delete --password-file=/etc/rsyncd.pwd /data/ [email protected]::backup

4、Rsync 同步参数说明

-vzrtopg里的v是verbose,z是压缩,r是recursive,topg都是保持文件原有属性如属主、时间的参数。
–progress是指显示出详细的进度情况
–delete是指如果服务器端删除了这一文件,那么客户端也相应把文件删除

5、rsync常用参数:

#rsync [option] 源路径 目标路径
其中[option]为:

a:使用archive模式,等于-rlptgoD,即保持原有的文件权限
z:表示传输时压缩数据
v:显示到屏幕中
e:使用远程shell程序(可以使用rsh或ssh)

–delete:精确保存副本,源主机删除的文件,目标主机也会同步删除
–include=PATTERN:不排除符合PATTERN的文件或目录
–exclude=PATTERN:排除所有符合PATTERN的文件或目录
–password-file:指定用于rsync服务器的用户验证密码

六、rsync常见错误排错

1、

rsync: failed to connect to 118.244.216.177: No route to host (113)

rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.6]

原因:防火墙屏蔽了端口

解决:打开873段考

iptables -i INPUT -p tcp --dport 873 -j ACCEPT
iptables -L

如果以上指令不行,可以直接停掉防火墙

/etc/init.d/iptables stop

2、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at main.c(1506) [Receiver=3.0.7]

检查密码文件设置权限 chmod 600 /etc/rsyncd.pwd

3、

@ERROR: auth failed on module xxxxx

rsync: connection unexpectedly closed (90 bytes read so far)

rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这是因为密码设错了, 无法登入成功, 请检查一下 rsyncd.scrt 中的密码, 二端是否一致?

4、

password file must not be other-accessible

continuing without password file

Password:

这表示 rsyncd.pwd 的档案权限属性不对, 应设为 600。

5、

@ERROR: chroot failed

rsync: connection unexpectedly closed (75 bytes read so far) 

rsync error: error in rsync protocol data stream (code 12) at io.c(150)

这通常是您的 rsyncd.conf 中的 path 路径所设的那个目录并不存在所致.请先用 mkdir开设好要备份目录

6、

@ERROR: access denied to www from unknown (192.168.1.123)

rsync: connection unexpectedly closed (0 bytes received so far) [receiver]

rsync error: error in rsync protocol data stream (code 12) at io.c(359)

最后原因终于找到了。因为有两个网段都需要同步该文件夹内容,但没有在hosts allow 后面添加另一个IP段

hosts allow = 192.168.1.0/24

改为

hosts allow = 192.168.1.0/24 192.168.2.0/24

重新启动rsync服务,问题解决

7、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at 
main.c(1506) [Receiver=3.0.7]

client端没有设置/etc/rsyncd.pwd这个文件,而在使用rsync命令的时候,加了这个参数–password-file=/etc/rsyncd.pwd

8、

rsync: recv_generator: mkdir "/teacherclubBackup/rsync……" failed: No space left on device (28)

*** Skipping any contents from this failed directory ***

磁盘空间满了

9、

rsync: opendir "/backup" (in dtsChannel) failed: Permission denied (13)

同步目录的权限设置不对,改为755

10、

rsync: read error: Connection reset by peer (104)

rsync error: error in rsync protocol data stream (code 12) at io.c(759) [receiver=3.0.5]

未启动xinetd守护进程

[root@CC02 /]# service xinetd start

11、

rsync: unable to open configuration file "/etc/rsyncd.conf": No such file or directory

xnetid查找的配置文件位置默认是/etc下,在/etc下找不到rsyncd.conf文件

12、

rsync: failed to connect to 203.100.192.66: Connection timed out (110)

rsync error: error in socket IO (code 10) at clientserver.c(124) [receiver=3.0.5]

连接服务器超时,检查服务器的端口netstat –tunlp,远程telnet测试

13、我需要在防火墙上开放哪些端口以适应rsync?

视情况而定。rsync可以直接通过873端口的tcp连接传文件,也可以通过22端口的ssh来进行文件传递,但你也可以通过下列命令改变它的端口:

rsync --port 8730 otherhost::

或者

rsync -e 'ssh -p 2002' otherhost:

14、我如何通过rsync只复制目录结构,忽略掉文件呢?

rsync -av --include '*/' --exclude '*' source-dir dest-dir

15、为什么我总会出现”Read-only file system”的错误呢?

看看是否忘了设”read only = no”了

16、

@ERROR: chroot failed

rsync error: error starting client-server protocol (code 5) at 
main.c(1522) [receiver=3.0.3]

原因:

服务器端的目录不存在或无权限。创建目录并修正权限可解决问题。

17、

@ERROR: auth failed on module backup

rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

原因:
服务器端该模块(tee)需要验证用户名密码,但客户端没有提供正确的用户名密码,认证失败。提供正确的用户名密码解决此问题。

18、

@ERROR: Unknown module ‘bcakup’

rsync error: error starting client-server protocol (code 5) at main.c(1522) [receiver=3.0.3]

原因:
服务器不存在指定模块。提供正确的模块名或在服务器端修改成你要的模块以解决问题。

19、权限无法复制。去掉同步权限的参数即可。(这种情况多见于Linux向Windows的时候)
(备份本地目录/data/到服务端192.168.1.100)