inotifywait 用于监控某个文件目录,当这个目录下发生变化的时候打印变化信息
详细介绍:https://blog.csdn.net/ck784101777/article/details/98059643
rsyn 用于同步文件目录,如目录1与目录2,执行rsyn命令后目录2将被同步
详细介绍:https://blog.csdn.net/ck784101777/article/details/98056201
实现此案例需要按照如下步骤进行。
步骤一:准备两台主机
svr7,pc207
双方的目录均为/var/www/html/,如果安装了httpd,此目录会自动出现。
1)确认svr7的目录内容
- [root@svr7 ~]# yum -y install httpd
- .. ..
- [root@svr7 ~]# ls /var/www/html/ //向目录下提供一些测试文件
- libreoffice
2)确认pc207的目录内容
- [root@pc207 ~]# yum -y install httpd
- .. ..
- [root@pc207 ~]# ls /var/www/html //初始目录无数据
- [root@pc207 ~]#
步骤二:为svr7配置到pc207的SSH密钥对验证,实现免密码交互
1)检查当前用户是否已经有可用的SSH密钥对文件
- [root@svr7 ~]# ls ~/.ssh/id_*
- /root/.ssh/id_rsa /root/.ssh/id_rsa.pub
如果找不到id_rsa、id_rsa.pub密钥对文件,则需要执行下列操作创建:
- [root@svr7 ~]# ssh-keygen
- 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:
- 00:a7:cb:2d:9d:b8:8a:df:f5:ff:5b:ed:bd:04:10:fe root@svr7
- The key's randomart image is:
- +--[ RSA 2048]----+
- | . . . |
- | + . . |
- | . . o |
- | . = o o |
- | = + S E |
- | o .. |
- | . . ...|
- | . o . . ....|
- |..o . ....o. .+|
- +-----------------+
2)将当前用户的SSH公钥部署到远程主机
- [root@svr7 ~]# ssh-copy-id root@192.168.4.207
- The authenticity of host '192.168.4.207 (192.168.4.207)' can't be established.
- ECDSA key fingerprint is d3:16:2c:9a:9d:91:28:c8:74:9c:af:2d:04:82:c9:66.
- Are you sure you want to continue connecting (yes/no)? yes //首次连yes确认
- root@192.168.4.207's password: //验证对方的密码
- Number of key(s) added: 1
- Now try logging into the machine, with: "ssh 'root@192.168.4.207'"
- and check to make sure that only the key(s) you wanted were added.
3)验证免密码登录效果
- [root@svr7 ~]# ssh root@192.168.4.207
- Last login: Fri Jan 13 09:52:08 2017 from 192.168.4.110
- [root@pc207 ~]# //确认已免密码连入远程主机
- [root@pc207 ~]# exit //退出SSH登录环境
- 登出
- Connection to 192.168.4.207 closed.
- [root@svr7 ~]# //已反对原客户机
步骤三:编写同步脚本并测试效果
1)编写脚本文件/root/isync.sh
- [root@svr7 ~]# vim /root/isync.sh
- #!/bin/bash
- FROM_DIR="/var/www/html/"
- RSYNC_CMD="rsync -az --delete $FROM_DIR root@192.168.4.207:/var/www/html"
- while inotifywait -rqq -e modify,move,create,delete,attrib $FROM_DIR
- do
- $RSYNC_CMD
- done &
- [root@svr7 ~]# chmod +x /root/isync.sh
2)运行脚本
- [root@svr7 ~]# /root/isync.sh
- [root@svr7 ~]# pgrep -l inotify //确认任务在运行
- 56494 inotifywait
3)测试同步效果
在svr7上向/var/www/html/目录下添加一个测试网页(触发同步):
- [root@svr7 ~]# touch /var/www/html/a.txt
- [root@svr7 ~]# ls /var/www/html/
- a.txt libreoffice
在pc207上检查/var/www/html/目录,内容应该已经与svr7上的同名目录一致:
- [root@pc207 ~]# ls /var/www/html
- a.txt libreoffice
4)结束测试后,在svr7上停止监控任务
- [root@svr7 ~]# pkill -9 inotify
- [root@svr7 ~]# pgrep -l inotify //确认已没有监控任务
- [root@svr7 ~]#