阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Linux安装rsync和inotify实现文件夹实时同步

171次阅读
没有评论

共计 1819 个字符,预计需要花费 5 分钟才能阅读完成。

Linux 安装 rsync 和 inotify 实现文件夹实时同步

需求说明

在 web 服务器中,作为代码发布机 A,文件同步到服务器 B,C,D 等集群中,可以忽略某个文件和目录。

A 服务器:内网 IP: 192.168.1.2

B 服务器:内网 IP:192.168.1.3

A 和 B 的 www 用户,或者 root 用户免密登录。

Linux 安装 rsync 和 inotify 实现文件夹实时同步

1. 安装 rsync

A 和 B 都做

yum -y install xinetd
yum -y install rsync

chkconfig rsync on

service xinetd restart
systemctl restart xinetd

A 上操作:

rsync -av root@192.168.1.3:/rsynctest/1.txt /root

B 上操作

rsync -av /rsynctest/2.txt root@192.168.1.2:/root
rsync -av -e "ssh -p 22" /rsynctest/2.txt root@192.168.1.2:/root【如果 ssh 的开启的端口不是 22 则用 - e 指定 ssh 端口】

2. 安装 inotify

只在 A 上操作即可。

安装 inotify-tools
wget js.funet8.com/centos_software/inotify-tools-3.14.tar.gz
tar -zxvf inotify-tools-3.14.tar.gz
cd inotify-tools-3.14
./configure
make
make install

inotifywait -m /root【查看 inotify-tools 是否运行正常】


新开一个终端:
[root@localhost ~]# cd /root
[root@localhost ~]# touch bb.txt

监控到

# inotifywait -m /root
Setting up watches.
Watches established.
/root/ OPEN .bash_profile
/root/ ACCESS .bash_profile
/root/ CLOSE_NOWRITE,CLOSE .bash_profile
/root/ OPEN .bashrc
/root/ ACCESS .bashrc
/root/ CLOSE_NOWRITE,CLOSE .bashrc
/root/ CREATE bb.txt
/root/ OPEN bb.txt
/root/ ATTRIB bb.txt
/root/ CLOSE_WRITE,CLOSE bb.txt

网站实时同步脚本

test.sh 为要运行网站实时同步脚本 其中定义了要同步的网站的路径,要同步到的 ip 地址,哪些后缀名的文件忽略监控,同步的用户名,同步的文件列表,哪些文件不需要同步。

cat test.sh
#!/bin/sh
SRC=/data/wwwroot/web/www.test.com/ #代码发布服务器目录
DST=/data/wwwroot/web/www.test.com/ #目标服务器目录

IP="192.168.1.3 192.168.1.4" # 这里可以用 hostname
USER=www
inotifywait -mrq $SRC -e modify,delete,create,close_write,attrib | while read D E F  
      do  
              for i in $IP
              do
                      #排除后缀名和目录
                      /usr/bin/rsync -e 'ssh -p 60920' \
                      -ahqzt --exclude "*.swp" \
                      --exclude "*.svn" \
                      --exclude "test/" \
                      --exclude "runtime/" \
                      --delete $SRC $USER@$i:$DST
              done
      done

运行:

增加权限:
chmod +x test.sh

后台运行:
nohup ./test.sh > nohup_test.com 2>&1 &

生成一个文件才能触发文件同步
touch /data/wwwroot/web/www.test.com/test_rsync_`date +%Y%m%d-%H:%M:%S`.html

删除测试文件
rm -rf /data/wwwroot/web/www.test.com/test_rsync*.html

测试文件是否同步

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-05-24发表,共计1819字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中