inotify+rsync实时同步

Web1是主 Web2是从,现实现Web2实时同步Web1的内容

[root@Web2 /]# useradd rsync
[root@Web2 /]# echo example | passwd --stdin rsync
[root@Web2 /]# chmod -R 755 /var/www/html/
[root@Web2 /]# chown rsync /var/www/html/
[root@Web2 /]# ls -ld /var/www/html/
drwxr-xr-x. 4 rsync root 4096 12月 27 17:30 /var/www/html/
[root@Web2 /]#

测试rsync的使用

[root@web1 ~]#rsync rsync@192.168.31.226:/
The authenticity of host '192.168.30.11 (192.168.30.11)' can't be established.
RSA key fingerprint is 11:19:2c:dc:1b:04:b1:50:cc:e2:f0:95:34:c8:2d:99.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.31.226' (RSA) to the list of known hosts.
rsync@192.168.30.11's password:
......
drwxr-xr-x           0 2014/12/09 14:46:15 sys
drwxrwxrwt        4096 2014/12/09 14:46:49 tmp
drwxr-xr-x        4096 2014/08/28 07:23:12 usr
drwxr-xr-x        4096 2014/11/03 19:45:44 var
[root@web1 ~]#

Web1主机操作
安装expect语言支持(可实现自动交互作用)

[root@Web1 /]# yum -y install expect

编写rsync传输脚本,需实现自动交互

[root@Web1 /]# vim /opt/rsync.sh
[root@Web1 /]# cat /opt/rsync.sh 
#!/usr/bin/expect
spawn rsync -az /var/www/html/  rsync@192.168.31.226:/var/www/html/
expect "password:"
send "example\n"
expect eof
exit
[root@Web1 /]# chmod +x /opt/rsync.sh

测试是否自动交互脚本是否可以成功执行rsync命令进行文件同步
Web1主机操作

[root@Web1 /]# ls /var/www/html/
lost+found  upload
[root@Web1 /]# ls /var/www/html/
index.html link.php php.php upload
[root@Web1 /]

Web2主机操作

[root@Web2 ~]# rm -rf /var/www/html/*
[root@Web2 ~]# ls /var/www/html/
[root@Web2 ~]#

Web1主机操作

[root@ Web1 /]# /opt/rsync.sh 
spawn rsync -az /var/www/html/ rsync@192.168.31.226: /var/www/html/
rsync@192.168.31.226's password: 
[root@ Web1 /]# 

Web2主机操作

[root@Web2 ~]# ls /var/www/html/
index.html link.php php.php upload
[root@Web2 ~]#

在Web1安装inotfywait

[root@Web1 /]#tar -zxf /root/inotify-tools-3.14.tar.gz -C /usr/src/
[root@Web1/]#cd /usr/src/inotify-tools-3.14/
[root@Web1 inotify-tools-3.14]# ./configure && make && make install

在Web1编写inotfywait文件监控+实时同步脚本

[root@Web1 /]# vim /opt/inotifywait.sh
[root@Web1 /]# cat /opt/inotifywait.sh
#!/bin/bash
/usr/local/bin/inotifywait -mrq -e modify,move,create,delete,attrib /var/www/html |
while read  X  Y  Z ;
do
/opt/rsync.sh &>/dev/null
done&
[root@Web1 /]# chmod +x /opt/inotifywait.sh
[root@Web1 /]# /opt/inotifywait.sh

测试Web2是否能实时同步Web1

[root@Web1 /]# mkdir  /var/www/html/1.txt
[root@Web2 /]# ls /var/www/html/

expect 命令详解

comments powered by Disqus