rsync同步、使用脚本后台自动同步

    科技2022-07-10  114

    作者:卖兔子的萝北 分类:学习笔记(Linux云计算)

    一、环境准备

    准备两台虚拟机

    svr7192.168.4.7pc207192.168.4.207

    关闭防火墙、SELinux设置为宽松状态、安装rsync

    二、rsync概述

    支持本地复制,与ssh、rsync主机同步

    三、同步操作

    rsync [选项] 源路径 目标路径 -av 基本同步,显示传输文件 –delete 删除目标多余的路径 -n 测试同步 -z:传输过程中启用压缩/解压 1.本地同步

    -av 基本同步组合 [root@svr7 ~]# mkdir /mydir /todir [root@svr7 ~]# cp /etc/passwd /etc/shadow /mydir/ [root@svr7 ~]# echo 122 > /mydir/1.txt [root@svr7 ~]# rsync -av /mydir/ /todir/ sending incremental file list 1.txt [root@svr7 ~]# cat /todir/1.txt 122

    -av --delete 同步时删除目标多余的文件 [root@svr7 ~]# touch /todir/2.txt [root@svr7 ~]# ls /todir/ 1.txt 2.txt passwd shadow [root@svr7 ~]# rsync -av --delete /mydir/ /todir/ sending incremental file list deleting 2.txt ./ sent 116 bytes received 28 bytes 288.00 bytes/sec total size is 3,504 speedup is 24.33 [root@svr7 ~]# ls /todir/ 1.txt passwd shadow [root@svr7 ~]# ls /mydir/ 1.txt passwd shadow

    2.远程同步 rsyns+SSH同步 与远程的SSH目录保持同步 下行(下载): rsync […] user@host:远程目录 本地目录 上行(上传):rsync […] 本地目录 user@host:远程目录 [root@svr7 ~]# rsync -av --delete /mydir/ root@192.168.4.207:/opt [root@svr7 ~] ls /opt 1.txt passwd shadow

    3.实时同步 虚拟机A的/mydir 目录的内容与虚拟机B的/opt进行同步 实现ssh无密码认证(公钥与私钥) 1.生成公钥与私钥 [root@svr7 ~]# ssh-keygen [root@svr7 ~]# ls /root/.ssh/ id_rsa id_rsa.pub known_hosts 2.传递公钥 [root@svr7 ~]# ssh-copy-id root@192.168.4.207 [root@svr7 ~]# ssh root@192.168.4.207 #连接测试 Last login: Tue Sep 22 18:15:15 2020 from 192.168.4.7 [root@pc207 ~]# [root@svr7 ~]# rsync -av --delete /mydir/ root@192.168.4.207:/opt sending incremental file list #再次传递时无需密码

    sent 113 bytes received 12 bytes 250.00 bytes/sec total size is 3,504 speedup is 28.03 3.监控目录内容变化工具 (自己准备安装包) 基本用法 – inotifywait [选项] 目标文件夹 • 常用命令选项 – -m,持续监控(捕获一个事件后不退出) – -r,递归监控、包括子目录及文件 – -q,减少屏幕输出信息 – -e,指定监视的 modify、move、create、delete、attrib 等事件类别 [root@svr7 ~]# yum -y install gcc make [root@svr7 ~]# tar -xf inotify-tools-3.13.tar.gz -C /usr/local/ [root@svr7 ~]# cd /usr/local/inotify-tools-3.13/ [root@svr7 inotify-tools-3.13]# ./configure --prefix=/opt/myrpm [root@svr7 inotify-tools-3.13]# make && make install [root@svr7 ~]# ls /opt/myrpm/ bin include lib share [root@svr7 ~]# /opt/myrpm/bin/inotifywait -rq /mydir/ #监控目录 书写shell脚本(把两个程序关联起来) 脚本:可以运行一个文件,实现某种功能 中文:新建用户zhangsan shell: useradd zhangsan 重复性:循环解决 死循环:while循环 while 条件 do 重复执行的事情 done

    [root@svr7 /]# vim /etc/rsync.sh while /opt/myrpm/bin/inotifywait -rqq /mydir/ do rsync -a --delete /mydir/ root@192.168.4.207:/opt done [root@svr7 /]# chmod a+x /etc/rsync.sh #赋予执行权限 [root@svr7 /]# /etc/rsync.sh & #后台运行脚本程序

    Processed: 0.010, SQL: 8