rsync

一、rsync概述

rsync是linux系统下的数据镜像备份工具,使用快速增量备份工具remote sync可以远程同步,可以在不同主机之间进行同步,可以实现全量备份与增量备份,保持链接和权限,且采用优化的同步算法,传输前执行压缩,因此非常适合用于架构集中式的备份或异地备份等应用。同时rsync支持本地复制,或者与其他ssh、rsync主机同步。

二、rsync特性和优点

1)可以镜像保存整个目录树和文件系统
2)可以很容易做到保持原来文件的权限、时间、软硬链接等等。
3)无须特殊权限即可安装
4)快速:第一次同步时rsync复制全部内容,但在下一次值传输修改过的内容
5)压缩传输:rysnc在传输的过程中可以实行压缩及解压缩操作,可以使用更少的带宽
6)安全:可以使用scp、ssh等方式来进行文件传输
7)支持匿名传输,以方便进行网站镜像
8)选择性保持:符号链接、硬链接、文件属性、权限、时间等

三、rsync原理

1、运行模式和端口

1)采用C/S模式(实际上是一个点到点的传输,直接使用rsync命令即可完成)
2)rsync监听的端口是:873

2、四个名字的解释

1)发起端:负责发起rsync同步操作的客户端叫做发起端。通知服务器我要备份你的数据
2)备份源:负责响应来自客户端rsync同步操作的服务器叫做备份源,需要备份的服务器
3)服务端:运行rsyncd服务,一般来说,需要备份的服务器
4)客户端:存放备份数据。

3、数据同步方式

1)推push:一台主机负责吧数据传送给其他主机,服务器开销很大,比较适合后端服务器少的情况
2)拉pull:所有主机定时去找一台主机拉数据,可能就会导致数据缓慢
推:目的主机配置为rsync服务器,源主机周期性的使用rysnc命令把要同步的目录推过去(需要备份的机器是客户端,存储备份的机器是服务端)
拉:源主机配置为rysnc服务器,目的主机周期性的使用rync命令把要同步的目录拉过来(需要备份的机器是服务端,存储备份的机器是客户端)

4、rsync常用命令

//rsync命令:

rsync  —a  fast,versatile(通用的),remote(and local)file-copying tool  

//常用选项:

    -n:测试是否能执行成功 

    -v:显示详细的过程

    -a:归档

    -z:在传输的过程中压缩

    -r:递归复制 

    -P:保持原有属性 

    -p:perm,保持原有权限 

    -e:ssh,表示使用ssh的加密功能 

    -q:quit,静默模式

    -g:保留原文件的属组

    -o:保留原文件的属主

    -l:保留原文件的连接文件 

 

 

四、本地及远程rsync同步

 

//安装rsync
[root@RS1 ~]# yum -y install rsync

//关闭防火墙和SElinux
[root@RS1 ~]# systemctl stop firewalld
[root@RS1 ~]# setenforce 0
[root@RS2 ~]# systemctl stop firewalld
[root@RS2 ~]# setenforce 0

开始本地同步

//同步本地文件
[root@RS1 ~]# ls
anaconda-ks.cfg 
[root@RS1 ~]# rsync -avz anaconda-ks.cfg /opt/abc
sending incremental file list
anaconda-ks.cfg

sent 766 bytes  received 35 bytes  1,602.00 bytes/sec
total size is 1,185  speedup is 1.48
[root@RS1 ~]# ll anaconda-ks.cfg /opt/abc
-rw-------. 1 root root 1185 Feb 26 02:10 anaconda-ks.cfg
-rw-------  1 root root 1185 Feb 26 02:10 /opt/abc
#其实就和cp一样,和cp没有任何区别

//同步本地目录
[root@RS1 ~]# cp dead.letter haha/
[root@RS1 ~]# tree haha/
haha/
└── dead.letter

0 directories, 1 file
[root@RS1 ~]# cd haha/
[root@RS1 haha]# mkdir ABC
[root@RS1 haha]# echo 'aabb' > ABC/index
[root@RS1 haha]# cd
[root@RS1 ~]# tree haha/
haha/
├── ABC
│   └── index
└── dead.letter

1 directory, 2 files
[root@RS1 ~]# rsync -avz haha /opt/666
sending incremental file list
created directory /opt/666
haha/
haha/dead.letter
haha/ABC/
haha/ABC/index

sent 421 bytes  received 101 bytes  1,044.00 bytes/sec
total size is 223  speedup is 0.43
[root@RS1 ~]# ls /opt/
666  abc  containerd  data  dir1  dir2

//同步多个源
[root@RS1 ~]# rsync -avz anaconda-ks.cfg haha /opt/aabb
sending incremental file list
created directory /opt/aabb
anaconda-ks.cfg
haha/
haha/dead.letter
haha/ABC/
haha/ABC/index

sent 1,159 bytes  received 117 bytes  2,552.00 bytes/sec
total size is 1,408  speedup is 1.10
[root@RS1 ~]# ls /opt/
666  aabb  abc  containerd  data  dir1  dir2
[root@RS1 ~]# tree /opt/aabb/
/opt/aabb/
├── anaconda-ks.cfg
└── haha
    ├── ABC
    │   └── index
    └── dead.letter

2 directories, 3 files

 

五、同步文件到远程主机

[root@RS1 ~]# rsync -avz anaconda-ks.cfg root@192.168.186.131:/tmp/
The authenticity of host '192.168.186.131 (192.168.186.131)' can't be established.
ECDSA key fingerprint is SHA256:+tvDQCu4JzfrZXBekLFvNB+FH7aKP7NrYKmUhF0B+lU.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.186.131' (ECDSA) to the list of known hosts.
root@192.168.186.131's password: 
sending incremental file list
anaconda-ks.cfg

sent 766 bytes  received 35 bytes  84.32 bytes/sec
total size is 1,185  speedup is 1.48

[root@RS2 ~]# ls /tmp/
anaconda-ks.cfg

 

将远程主机文件同步到本地

//做免密登录
[root@RS1 ~]# 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:
SHA256:Vfk1hKh6T80u+AwkbOb+BRFQTpM2ryeT7Dc7qctT/YE root@RS1
The key's randomart image is:
+---[RSA 2048]----+
|       .o=. o.o. |
|        o+oo.. ..|
|        .o=  . ..|
|      .  o..  .  |
|       =Soo + .  |
|      +.oB.+ E . |
|       .o.O.o . .|
|      . .++B . . |
|       ..=*+=    |
+----[SHA256]-----+

[root@RS1 ~]# ssh-copy-id root@192.168.186.131
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.186.131's password: 

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@192.168.186.131'"
and check to make sure that only the key(s) you wanted were added.

//远程主机同步到本地(绝对路径)
[root@RS1 ~]# rsync -avz /root/haha/ root@192.168.186.131:/tmp/
sending incremental file list
./
dead.letter
ABC/
ABC/index

sent 403 bytes  received 65 bytes  936.00 bytes/sec
total size is 223  speedup is 0.48

[root@RS2 ~]# tree /tmp/
/tmp/
├── ABC
│   └── index
└── dead.letter

1 directory, 2 files

 

六、rsync+inotify

环境说明:

 

服务器类型IP地址应用操作系统
源服务器 192.168.186.130 rsync
inotify-tools
脚本
redhat 8
目标服务器 192.168.186.131 rsync redhat 8

 

需求:

  • 把源服务器上/etc目录实时同步到目标服务器的/tmp/下

 

在目标服务器上做以下操作:

//安装rsync服务端软件
[root@RS2 ~]# yum -y install rsync

//设置rsyncd.conf配置文件
[root@RS2 ~]# vim /etc/rsyncd.conf

log file = /var/log/rsyncd.log    
pidfile = /var/run/rsyncd.pid     
lock file = /var/run/rsync.lock   
secrets file = /etc/rsync.pass    

[opt]                 path = /tmp/          
comment = sync etc from client
uid = root        
gid = root        
port = 873        
ignore errors     
use chroot = no       
read only = no    
list = no     
max connections = 200     
timeout = 600     
auth users = admin        

//创建用户认证文件
[root@RS2 ~]# echo 'admin:123456' > /etc/rsync.pass
[root@RS2 ~]# cat /etc/rsync.pass
admin:123456

//设置文件权限
[root@RS2 ~]# chmod 600 /etc/rsync*
[root@RS2 ~]# ll /etc/rsync*
-rw------- 1 root root 410 May 11 17:28 /etc/rsyncd.conf
-rw------- 1 root root  13 May 11 17:29 /etc/rsync.pass

//启动rsync服务
[root@RS2 ~]# rsync --daemon
[root@RS2 ~]# ss -antl
State  Recv-Q   Send-Q      Local Address:Port     Peer Address:Port  
LISTEN 0        128               0.0.0.0:22            0.0.0.0:*     
LISTEN 0        128               0.0.0.0:9000          0.0.0.0:*     
LISTEN 0        5                 0.0.0.0:873           0.0.0.0:*     
LISTEN 0        128                  [::]:22               [::]:*     
LISTEN 0        5                    [::]:873              [::]:*     

 

在源服务器上做以下操作:

//安装rsync服务端软件
[root@RS1 ~]# yum -y install rsync

//创建认证密码文件
[root@RS1 ~]# echo '123456' > /etc/mypass
[root@RS1 ~]# cat /etc/mypass 
123456

//设置文件权限,只设置文件所有者具有读取、写入权限即可
[root@RS1 ~]# chmod 600 /etc/mypass 
[root@RS1 ~]# ll /etc/mypass 
-rw------- 1 root root 7 May 11 17:41 /etc/mypass

//在源服务器上创建测试目录,然后在源服务器运行以下命令
[root@RS1 ~]# rsync -avH --port 873 --progress --delete /root/anaconda-ks.cfg admin@192.168.186.131::opt --password-file=/etc/mypass
sending incremental file list
anaconda-ks.cfg
          1,185 100%    0.00kB/s    0:00:00 (xfr#1, to-chk=0/1)

sent 1,294 bytes  received 43 bytes  2,674.00 bytes/sec
total size is 1,185  speedup is 0.89

[root@RS2 ~]# ls /tmp/
anaconda-ks.cfg

//安装inotify-tools工具,实时触发rsync进行同步
[root@RS1 ~]# yum -y install inotify-tools


//查看服务器内核是否支持inotify
[root@RS1 ~]# ll /proc/sys/fs/inotify/
total 0
-rw-r--r-- 1 root root 0 May 11 17:53 max_queued_events
-rw-r--r-- 1 root root 0 May 11 17:53 max_user_instances
-rw-r--r-- 1 root root 0 May 11 17:53 max_user_watches
//如果有这三个max开头的文件则表示服务器内核支持inotify

//写同步脚本
[root@RS1 ~]# mkdir /scripts
[root@RS1 ~]# touch /scripts/inotify.sh
[root@RS1 ~]# chmod 755 /scripts/inotify.sh
[root@RS1 ~]# ll /scripts/inotify.sh
-rwxr-xr-x 1 root root 0 May 11 17:58 /scripts/inotify.sh

[root@RS1 ~]# vim /scripts/inotify.sh 

#bin/bash
host=192.168.186.131      
src=/opt        
des=opt     
password=/etc/mypass            
user=admin          
inotifywait=/usr/bin/inotifywait

$inotifywait -mrq --timefmt '%Y%m%d %H:%M' --format '%T %w%f%e' -e modify,delete,create,attrib $src \
        | while read files;do
    rsync -avzP --delete  --timeout=100 --password-file=${password} $src $user@$host::$des
        echo "${files} was rsynced" >>/tmp/rsync.log 2>&1
done

//启动脚本
[root@RS1 ~]# nohup /bin/bash /scripts/inotify.sh &
[1] 22546
[root@RS1 ~]# nohup: ignoring input and appending output to 'nohup.out'

[root@RS1 ~]# ps -ef|grep inotify
root      22546   2260  0 18:25 pts/0    00:00:00 /bin/bash /scripts/inotify.sh
root      22547  22546  0 18:25 pts/0    00:00:00 /usr/bin/inotifywait -mrq --timefmt %Y%m%d %H:%M --format %T %w%f%e -e modify,delete,create,attrib /opt
root      22548  22546  0 18:25 pts/0    00:00:00 /bin/bash /scripts/inotify.sh
root      22619   2260  0 18:26 pts/0    00:00:00 grep --color=auto inotify

//在源服务器上生成一个新文件
[root@RS1 opt]# touch abc
[root@RS1 ~]# echo 'ccccccccc' > /opt/abc

//查看inotify生成的日志
[root@RS1 opt]# tail /tmp/rsync.log
20210511 18:34 /opt/abcMODIFY was rsynced
//从日志上可以看到,我们生成了一个abc文件,并且添加了内容到其里面

//在目标服务器查看
[root@RS2 ~]# ll /tmp/opt/
total 8
-rw-r--r-- 1 root root 13 May 11 18:34 abc

[root@RS2 ~]# cat /tmp/opt/abc 
ccccccccc

 

 

设置脚本开机自动启动:

[root@RS1 ~]# chmod +x /etc/rc.d/rc.local
[root@RS1 ~]# ll /etc/rc.d/rc.local
-rwxr-xr-x. 1 root root 474 Feb 26  2019 /etc/rc.d/rc.local
[root@RS1 ~]# echo 'nohup /bin/bash /scripts/inotify.sh' >> /etc/rc.d/rc.local
[root@RS1 ~]# tail /etc/rc.d/rc.local
#
# In contrast to previous versions due to parallel execution during boot
# this script will NOT be run after all other services.
#
# Please note that you must run 'chmod +x /etc/rc.d/rc.local' to ensure
# that this script will be executed during boot.

touch /var/lock/subsys/local

nohup /bin/bash /scripts/inotify.sh
[root@RS1 ~]# tree /opt/
/opt/
├── abc
├── cccd
├── containerd
│   ├── bin
│   └── lib
└── test
    └── abc

[root@RS2 ~]# tree /tmp/opt/
/tmp/opt/
├── abc
├── cccd
├── containerd
│   ├── bin
│   └── lib
└── test
    └── abc

 

 

[root@RS2 ~]# vim /usr/lib/systemd/system/rsyncd.service

[Unit]
Description=fast remote file copy program daemon
ConditionPathExists=/etc/rsyncd.conf

[Service]
EnvironmentFile=/etc/sysconfig/rsyncd
ExecStart=/usr/bin/rsync --daemon --no-detach "$OPTIONS"

[Install]
WantedBy=multi-user.target
[root@RS2 ~]# vim /usr/lib/systemd/system/rsyncd.service
[root@RS2 ~]# echo 'OPTIONS=""' > /etc/sysconfig/rsyncd
[root@RS2 ~]# systemctl enable --now rsyncd
Created symlink /etc/systemd/system/multi-user.target.wants/rsyncd.service → /usr/lib/systemd/system/rsyncd.service.

 

posted @ 2021-05-10 23:55  Raygussie  阅读(162)  评论(0编辑  收藏  举报