zoukankan      html  css  js  c++  java
  • rsync

    rsync简介

    rsync是linux系统下的数据镜像备份工具。使用快速增量备份工具Remote Sync可以远程同步,支持本地复制,或者与其他SSH、rsync主机同步。

    rsync特性

    rsync支持很多特性:

    • 可以镜像保存整个目录树和文件系统
    • 可以很容易做到保持原来文件的权限、时间、软硬链接等等
    • 无须特殊权限即可安装
    • 快速:第一次同步时rsync会复制全部内容,但在下一次只传输修改过的文件。rsync在传输数据的过程中可以实行压缩及解压缩操作,因此可以使用更少的带宽
    • 安全:可以使用scp、ssh等方式来传输文件,当然也可以通过直接的socket连接
    • 支持匿名传输,以方便进行网站镜像

    rsync的ssh认证协议

    rsync命令来同步系统文件之前要先登录remote主机认证,认证过程中用到的协议有2种:

    • ssh协议
    • rsync协议
    rsync server端不用启动rsync的daemon进程,只要获取remote host的用户名和密码就可以直接rsync同步文件
    rsync server端因为不用启动daemon进程,所以也不用配置文件/etc/rsyncd.conf
    

    ssh认证协议跟scp的原理是一样的,如果在同步过程中不想输入密码就用ssh-keygen -t rsa打通通道

    //这种方式默认是省略了 -e ssh 的,与下面等价:
    rsync -avz /SRC -e ssh root@192.168.23.143:/DEST 
        -a  //文件宿主变化,时间戳不变
        -z  //压缩数据传输
     
    //当遇到要修改端口的时候,我们可以:
    rsync -avz /SRC -e "ssh -p2222" root@192.168.23.142:/DEST  
    //修改了ssh 协议的端口,默认是22
    

    rsync命令

    -v, --verbose         详细模式输出
    -q, --quiet           精简输出模式
    -c, --checksum        打开校验开关,强制对文件传输进行校验
    -a, --archive         归档模式,表示以递归方式传输文件,并保持所有文件属性,等于-rlptgoD
    -r, --recursive       对子目录以递归模式处理
    -R, --relative        使用相对路径信息
    -b, --backup          创建备份,也就是对于目的已经存在有同样的文件名时,将老的文件重新命名为~filename。可以使用--suffix选项来指定不同的备份文件前缀。
    --backup-dir          将备份文件(如~filename)存放在在目录下。
    -suffix=SUFFIX        定义备份文件前缀
    -u, --update          仅仅进行更新,也就是跳过所有已经存在于DST,并且文件时间晚于要备份的文件。(不覆盖更新的文件)
    -l, --links           保留软链结
    -L, --copy-links      像对待常规文件一样处理软链接
    --copy-unsafe-links   仅仅拷贝指向SRC路径目录树以外的链接
    --safe-links          忽略指向SRC路径目录树以外的链接
    -H, --hard-links      保留硬链接
    -p, --perms           保持文件权限
    -o, --owner           保持文件属主信息
    -g, --group           保持文件属组信息
    -D, --devices         保持设备文件信息
    -t, --times           保持文件时间信息
    -S, --sparse          对稀疏文件进行特殊处理以节省DST的空间
    -n, --dry-run         显示哪些文件将被传输
    -W, --whole-file      拷贝文件,不进行增量检测
    -x, --one-file-system 不要跨越文件系统边界
    -B, --block-size=SIZE 检验算法使用的块尺寸,默认是700字节
    -e, --rsh=COMMAND     指定使用rsh、ssh方式进行数据同步
    --rsync-path=PATH     指定远程服务器上的rsync命令所在路径信息
    -C, --cvs-exclude     使用和CVS一样的方法自动忽略文件,用来排除那些不希望传输的文件
    --existing            仅仅更新那些已经存在于DST的文件,而不备份那些新创建的文件
    --delete              删除那些DST中SRC没有的文件
    --delete-excluded     同样删除接收端那些被该选项指定排除的文件
    --delete-after        传输结束以后再删除
    --ignore-errors       即使出现IO错误也进行删除
    --max-delete=NUM      最多删除NUM个文件
    --partial             保留那些因故没有完全传输的文件,以是加快随后的再次传输
    --force               强制删除目录,即使不为空
    --numeric-ids         不将数字的用户和组ID匹配为用户名和组名
    --timeout=TIME        IP超时时间,单位为秒
    -I, --ignore-times    不跳过那些有同样的时间和长度的文件
    --size-only           当决定是否要备份文件时,仅仅察看文件大小而不考虑文件时间
    --modify-window=NUM   决定文件是否时间相同时使用的时间戳窗口,默认为0
    -T --temp-dir=DIR     在DIR中创建临时文件
    --compare-dest=DIR    同样比较DIR中的文件来决定是否需要备份
    -P                    等同于 --partial
    --progress            显示备份过程
    -z, --compress        对备份的文件在传输时进行压缩处理
    --exclude=PATTERN     指定排除不需要传输的文件模式
    --include=PATTERN     指定不排除而需要传输的文件模式
    --exclude-from=FILE   排除FILE中指定模式的文件
    --include-from=FILE   不排除FILE指定模式匹配的文件
    --version             打印版本信息
    --address             绑定到特定的地址
    --config=FILE         指定其他的配置文件,不使用默认的rsyncd.conf文件
    --port=PORT           指定其他的rsync服务端口
    --blocking-io         对远程shell使用阻塞IO
    -stats                给出某些文件的传输状态
    --progress            在传输时显示传输过程
    --log-format=formAT   指定日志文件格式
    --password-file=FILE  从FILE中得到密码
    --bwlimit=KBPS        限制I/O带宽,KBytes per second
    -h, --help            显示帮助信息
    
    

    实现rsync自动同步

    环境

    主机名 IP地址 安装的应用 系统版本
    node1 192.168.23.143 rsync CentOS8
    node2 192.168.23.144 rsync CentOS8

    准备工作

    //YC1
    #安装rsync命令
    yum -y install rsync
    #关闭防火墙,selinux
    systemctl stop firewalld
    setenforce 0
    
    //YC2
    #安装rsync命令
    yum -y install rsync
    #关闭防火墙,selinux
    systemctl stop firewalld
    setenforce 0
    

    ssh协议本地同步

    //实现同步一个文件
    [root@YC1 ~]# echo haha > yyy
    [root@YC1 ~]# ls
    anaconda-ks.cfg  yyy
    [root@YC1 ~]# cat yyy 
    haha
    
    [root@YC1 ~]# mkdir /opt/yc
    [root@YC1 ~]# rsync -avz yyy /opt/yc
    sending incremental file list
    yyy
    
    sent 91 bytes  received 35 bytes  252.00 bytes/sec
    total size is 5  speedup is 0.04
    
    [root@YC1 ~]# cd /opt/yc
    [root@YC1 yc]# ls
    yyy
    [root@YC1 yc]# cat yyy
    haha
    [root@YC1 yc]# ll yyy /opt/yc/
    -rw-r--r-- 1 root root  5 May 10 22:32 yyy
    
    /opt/yc/:
    total 4
    -rw-r--r-- 1 root root 5 May 10 22:32 yyy
    
    //实现同步一个目录
    创建一个与下面tree显示相同的结构
    [root@YC1 ~]# tree test/
    test/
    ├── asd
    │   └── zxc
    └── yc
    
    2 directories, 1 file
    
    把test同步到/opt/yc中
    [root@YC1 ~]# rsync -avz test /opt/yc
    sending incremental file list
    test/
    test/asd/
    test/asd/zxc
    test/yc/
    
    sent 181 bytes  received 51 bytes  464.00 bytes/sec
    total size is 5  speedup is 0.02
    [root@YC1 ~]# tree /opt/yc
    /opt/yc
    └── test
        ├── asd
        │   └── zxc
        └── yc
    
    3 directories, 1 file
    
    [root@YC1 ~]# cat test/asd/zxc 
    haha
    [root@YC1 ~]# cat /opt/yc/test/asd/zxc 
    haha
    
    //同时同步多个文件或文件夹
    [root@YC1 ~]# mkdir /opt/abc
    [root@YC1 ~]# rsync -avz anaconda-ks.cfg test yyy /opt/haha
    sending incremental file list
    created directory /opt/haha
    anaconda-ks.cfg
    yyy
    test/
    test/asd/
    test/asd/zxc
    test/yc/
    
    sent 998 bytes  received 121 bytes  2,238.00 bytes/sec
    total size is 1,194  speedup is 1.07
    
    [root@YC1 ~]# tree /opt/haha
    /opt/haha
    ├── anaconda-ks.cfg
    ├── test
    │   ├── asd
    │   │   └── zxc
    │   └── yc
    └── yyy
    

    ssh协议非本地同步

    //在YC1上创建yyy文件
    [root@YC1 ~]# ls
    anaconda-ks.cfg  test  yyy
    [root@YC1 ~]# cat yyy
    haha
    [root@YC1 ~]# rsync -avz yyy root@192.168.23.144:/opt/
    root@192.168.23.144's password: 
    sending incremental file list
    yyy
    
    sent 91 bytes  received 35 bytes  28.00 bytes/sec
    total size is 5  speedup is 0.04
    
    //在YC2上的/opt目录下查看
    [root@YC2 ~]# cd /opt/
    [root@YC2 opt]# ls
    yyy
    [root@YC2 opt]# cat yyy 
    haha
    

    rsync自动同步

    rsync与传统的cp、tar备份方式相比,rsync具有安全性高、备份迅速、支持增量备份等优点,通过rsync可以解决对实时性要求不高的数据备份需求,例如定期的备份文件服务器数据到远端服务器,对本地磁盘定期做数据镜像等。
    随着应用系统规模的不断扩大,对数据的安全性和可靠性也提出的更好的要求,rsync在高端业务系统中也逐渐暴露出了很多不足,首先,rsync同步数据时,需要扫描所有文件后进行比对,进行差量传输。如果文件数量达到了百万甚至千万量级,扫描所有文件将是非常耗时的。而且正在发生变化的往往是其中很少的一部分,这是非常低效的方式。其次,rsync不能实时的去监测、同步数据,虽然它可以通过linux守护进程的方式进行触发同步,但是两次触发动作一定会有时间差,这样就导致了服务端和客户端数据可能出现不一致,无法在应用故障时完全的恢复数据。基于以上原因,rsync+inotify组合出现了!

    Inotify是一种强大的、细粒度的、异步的文件系统事件监控机制,linux内核从2.6.13起,加入了Inotify支持,通过Inotify可以监控文件系统中添加、删除,修改、移动等各种细微事件,利用这个内核接口,第三方软件就可以监控文件系统下文件的各种变化情况,而inotify-tools就是这样的一个第三方软件。
    在前面有讲到,rsync可以实现触发式的文件同步,但是通过crontab守护进程方式进行触发,同步的数据和实际数据会有差异,而inotify可以监控文件系统的各种变化,当文件有任何变动时,就触发rsync同步,这样刚好解决了同步数据的实时性问题

    配置文件说明

    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    # 用户认证配置文件,里面保存用户名称和密码,必须手动创建这个文件
    
    [etc_from_client]                 # 自定义同步名称
    path = /opt/                      # rsync目标服务端数据存放路径,源服务器的数据将同步至此目录
    comment = sync etc from client
    uid = root                        # 设置rsync运行权限为root
    gid = root                        # 设置rsync运行权限为root
    port = 873                        # 默认端口
    ignore errors                     # 表示出现错误忽略错误
    use chroot = no                   # 默认为true,修改为no,增加对目录文件软连接的备份
    read only = no                    # 设置rsync服务端为读写权限
    list = no                         # 不显示rsync服务端资源列表
    max connections = 200             # 最大连接数
    timeout = 600                     # 设置超时时间
    auth users = admin                # 执行数据同步的用户名,可以设置多个,用英文状态下逗号隔开
    hosts allow = 192.168.1.1         # 允许进行数据同步的源服务器IP地址,可以设置多个,用英文状态下逗号隔开
    hosts deny = 192.168.1.1          # 禁止数据同步的源服务器IP地址,可以设置多个,用英文状态下逗号隔开
    

    环境

    服务器类型 主机名 IP地址 安装的应用 系统版本
    源服务器 yc1 192.168.23.143 rsync
    inotify-tools
    CentOS 8
    目标服务器 yc2 192.168.23.144 rsync CentOS 8

    要求是将源服务器上/opt目录实时同步到目标服务器的/opt/下

    //准备工作
    yc1
    [root@yc1 ~]# systemctl disable --now firewalld
    [root@yc1 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    [root@yc1 ~]# setenforce 0
    [root@yc1 ~]# yum -y install rsync
    
    yc2
    [root@yc2 ~]# systemctl disable --now firewalld
    [root@yc2 ~]# sed -i "s/SELINUX=enforcing/SELINUX=disabled/g" /etc/selinux/config
    [root@yc2 ~]# setenforce 0
    [root@yc2 ~]# yum -y install rsync
    
    //查看源服务器上的opt目录中有那些文件
    [root@yc1 opt]# tree /opt/
    /opt/
    ├── abc
    ├── haha
    │   ├── anaconda-ks.cfg
    │   ├── test
    │   │   ├── asd
    │   │   │   └── zxc
    │   │   └── yc
    │   └── yyy
    └── yc
        └── test
            ├── asd
            │   └── zxc
            └── yc
    
    9 directories, 4 files
    
    • 配置目标服务器
    yc2
    //设置rsyncd.conf配置文件
    [root@yc2 ~]# vim /etc/rsyncd.conf
    log file = /var/log/rsyncd.log
    pidfile = /var/run/rsyncd.pid     
    lock file = /var/run/rsync.locksecrets file = /etc/rsync.pass
    
    [etc_from_client]     
    path = /opt/          
    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@yc2 ~]# echo 'admin:123456' > /etc/rsync.pass
    [root@yc2 ~]# cat /etc/rsync
    rsyncd.conf  rsync.pass   
    [root@yc2 ~]# cat /etc/rsync.pass 
    admin:123456
    
    //设置文件权限
    [root@yc2 ~]# chmod 600 /etc/rsync*
    [root@yc2 ~]# ll /etc/rsync*
    -rw------- 1 root root 396 May 11 20:43 /etc/rsyncd.conf
    -rw------- 1 root root  13 May 11 20:43 /etc/rsync.pass
    
    //启动rsync服务
    [root@yc2 ~]# rsync --daemon
    [root@yc2 ~]# 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              5                            0.0.0.0:873                       0.0.0.0:*            
    LISTEN         0              128                                *:80                              *:*            
    LISTEN         0              128                             [::]:22                           [::]:*            
    LISTEN         0              128                                *:443                             *:*            
    LISTEN         0              5                               [::]:873                          [::]:*   
    
    • 配置源服务器
    yc1
    //设置权限
    [root@yc1 ~]# chmod 600 /etc/rsync.pass
    [root@yc1 ~]# ll /etc/rsync.pass
    -rw------- 1 root root 7 May 11 20:50 /etc/rsync.pass
    
    //创建认证密码文件
    [root@yc1 ~]# echo '123456' > /etc/rsync.pass
    [root@yc1 ~]# cat /etc/rsync.pass
    123456
    
    //设置文件权限,只设置文件所有者具有读取、写入权限即可
    [root@node1 ~]# chmod 600 /etc/rsync.pass
    [root@node1 ~]# ll /etc/rsync.pass
    -rw------- 1 root root 7 May 11 20:50 /etc/rsync.pass
    
    • 开始同步文件
    [root@yc1 ~]# rsync -avH --port 873 --progress --delete /opt admin@192.168.23.144::etc_from_client --password-file=/etc/rsync.pass
    
    //运行完成后,在目标服务器上查看,在/opt目录下有dir目录,说明数据同步成功
    [root@yc2 opt]# tree /opt/
    /opt/
    └── opt
         ├── abc
         ├── haha
         │   ├── anaconda-ks.cfg
         │   ├── test
         │   │   ├── asd
         │   │   │   └── zxc
         │   │   └── yc
         │   └── yyy
         └── yc
             └── test
             ├── asd
             │   └── zxc
             └── yc
    
    • 实时触发rsync进行同步
    yc1
    //查看服务器内核是否支持inotify
    [root@yc1 ~]# ll /proc/sys/fs/inotify/
    total 0  
    -rw-r--r-- 1 root root 0 May 11 21:21 max_queued_events
    -rw-r--r-- 1 root root 0 May 11 21:21 max_user_instances
    -rw-r--r-- 1 root root 0 May 11 21:21 max_user_watches
    //如果有这三个max开头的文件则表示服务器内核支持inotify
    
    //安装inotify-tools工具
    [root@yc1 ~]# yum -y install inotify-tools
    
    //写同步脚本
    [root@yc1 ~]# mkdir /scripts
    [root@yc1 ~]# vim /scripts/inotify.sh
    #/bin/bash
    host=192.168.23.144                 # 目标服务器的ip(备份服务器)
    src=/opt                           # 在源服务器上所要监控的备份目录(此处可以自定义,但是要保证存在)
    des=etc_from_client                # 自定义的模块名,需要与目标服务器上定义的同步名称一致
    password=/etc/rsync.pass           # 执行数据同步的密码文件
    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@yc1 ~]# chmod 755 /scripts/inotify.sh
    [root@yc1 ~]# ll /scripts/inotify.sh
    -rwxr-xr-x 1 root root 718 May 11 21:26 /scripts/inotify.sh
    
    //启动脚本
    [root@yc1 ~]# nohup bash /scripts/inotify.sh &
    [1] 2718
    nohup: ignoring input and appending output to 'nohup.out'
    
    [root@yc1 ~]# ps -ef|grep inotify
    root        2718    1503  0 21:35 pts/0    00:00:00 bash /scripts/inotify.sh
    root        2719    2718  0 21:35 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        2720    2718  0 21:35 pts/0    00:00:00 bash /scripts/inotify.sh
    root        2722    1503  0 21:36 pts/0    00:00:00 grep --color=auto inotify
    
    //在源服务器上生成一个新文件
    [root@yc1 ~]# echo 'haha' > /opt/test
    
    //查看inotify生成的日志
    [root@yc1 ~]# tail /tmp/rsync.log 
    20210511 21:39 /opt/testCREATE was rsynced
    20210511 21:39 /opt/testMODIFY was rsynced
    
    //在目标服务器yc2上查看
    [root@yc2 ~]# cat /opt/opt/test
    haha
    
    • 设置脚本开机自动启动
    [root@yc1 ~]# chmod +x /etc/rc.d/rc.local
    [root@yc1 ~]# ll /etc/rc.d/rc.local
    -rwxr-xr-x. 1 root root 474 Mar 24  2020 /etc/rc.d/rc.local
    [root@node1 ~]# echo 'nohup /bin/bash /scripts/inotify.sh' >> /etc/rc.d/rc.local[root@node1 ~]# 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
    
    • 在目标服务器中设置rsync的开机自启动
    //编写rsyncd.service文件
    [root@yc2 ~]# 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@yc2 ~]# echo 'OPTIONS=""' > /etc/sysconfig/rsyncd
    
    //设置开机自启动
    [root@yc2 ~]# systemctl enable --now rsyncd
    
  • 相关阅读:
    团队项目-第一阶段冲刺2
    团队项目-第一阶段冲刺1
    第九周总结
    梦断代码阅读笔记02
    第八周总结
    团队会议个人领取任务
    梦断代码阅读笔记01
    Spring Boot 揭秘与实战(二) 数据缓存篇
    Spring Boot 揭秘与实战(二) 数据缓存篇
    Spring Boot 揭秘与实战(二) 数据缓存篇
  • 原文地址:https://www.cnblogs.com/Ycqifei/p/14753406.html
Copyright © 2011-2022 走看看