rsync+inotify文件同步

tech2022-10-25  92

rsync+inotify文件同步

机器:192.168.29.182/186

注:因为rsync基于sshd服务器,所以需要两台服务器互相做好免密登陆

1.生成密钥文件

[root@186 ~]# 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: SHA256:db3+pNp42nQq73gKKwhaPGfQahz5ma8iM0Jd4dhcmJU root@186 The key's randomart image is: +---[RSA 3072]----+ | +.. | | + E . | | =oo . . . | | .+=. . . . | | .o.= oS . | | . .O * . | |. + = o . o o| |. = . . o o.*o* | | . + ... .. *XB .| +----[SHA256]-----+

2.发送公钥给服务器

方法一:

[root@186 ~]# ssh-copy-id 192.168.29.182 [root@186 ~]# ssh 192.168.29.182 #这时ssh连接不需要密码 Last login: Wed Sep 2 17:37:23 2020 from 192.168.xx

方法二: 没有ssh-copy-id时,手动将182的id_rsa.pub内容添加到186的authorized_keys中

[root@182 ~]# vim /root/.ssh/id_rsa.pub ssh-rsa AAAAB3NzaC1yc2EAA... [root@186 ~]# vim /root/.ssh/authorized_keys ssh-rsa AAAAB3NzaC1yc2EAA... [root@182~]# ssh 192.168.29.186 #ssh测试 Last login: Wed Sep 2 17:36:32 2020 from 192.168.xx

3.安装 rsync+inotify 工具

# yum install -y rsync inotify-tools

4.编写文件触发 同步脚本

[root@186 service]# vim rsync.sh #这里没有写删除同步,防止误删 #!/usr/bin/env sh dir_src=/opt/service/vsftpd inotifywait -mrq --format '%T%e%w%f' --timefmt '%d/%m/%y %H:%M' -e modify,create,attrib ${dir_src} |\ while read line do echo ${line}1 >> /tmp/ftp_inotify.log rsync -zva ${dir_src}/ root@192.168.29.182:${dir_src} done

测试

186触发: [root@186 service]# sh rsync.sh & #后台执行脚本 [1] 21253 [root@186 service]# echo "186:hello 182" >> hello.txt [root@186 service]# echo "186:hello 182" >> /opt/service/vsftpd/hello.txt [root@186 service]# sending incremental file list #rsync.sh执行返回 ./ hello.txt hello.txt sent 304 bytes received 39 bytes 686.00 bytes/sec total size is 9,014 speedup is 26.28 sent 301 bytes received 36 bytes 674.00 bytes/sec total size is 9,014 speedup is 26.75 sending incremental file list 182验证: [root@182 ~]# cat /opt/service/vsftpd/hello.txt 186:hello 182 182触发: [root@182 service]# sh rsync.sh & #后台执行脚本 [root@182 service]# echo "182:hello 186" >> /opt/service/vsftpd/hello.txt sending incremental file list hello.txt sent 306 bytes received 42 bytes 232.00 bytes/sec total size is 9,028 speedup is 25.94 186验证: [root@186 ~]# cat /opt/service/vsftpd/hello.txt 186:hello 182 182:hello 186 大功告成!

5.添加至开机启动

# mv rsync.sh /opt/bin/inotify/ftp_rsync.sh # echo "sh /opt/bin/inotify/ftp_rsync.sh &>/dev/null &" >> /etc/rc.local 重启再次测试 # reboot
最新回复(0)