rsync+inotify
1、环境:两台Centos计算机直连,其服务器A的IP地址为192.168.1.124,服务器B的IP地址为192.168.1.121。
2、需求软件安装(ssh系统默认已经安装):
服务器A: yum install rsync inotify-tools
服务器B: yum install rsync
3、建立用户(备份执行用户) 建立用户:useradd rsync 设置密码:略 注意:两台服务器都需要建立用户(此处两天服务器建立了相同的用户,也可建立不同的用户)
4、建立ssh-key实现ssh自动连接 服务器A
建立公钥和私钥 [root@A ~]# su - rsync [rsync@A ~]$ ssh-keygen -t rsa(全部使用默认值,一直按回车即可) 完成后,此时会在/home/rsync/.ssh下,生成一对“公钥和私钥”,如下所示 [rsync@A .ssh]# ll total 12 -rw-------. 1 rsync rsync 1675 Oct 20 01:47 id_rsa -rw-r--r--. 1 rsync rsync 393 Oct 20 01:47 id_rsa.pub
然后,如下命令,将id_rsa.pub负责到服务器B上。 scp /home/rsync/.ssh/id.rsa.pub [email protected]:/home/rsync/
服务器B: 建立ssh存储“公钥”的目录: mkdir /home/rsync/.ssh chmod 700 /home/rsync/.ssh 将服务器A上传递的公钥,mv到/home/rsync/.ssh。如下命令 mv /home/rsync/id_rsa.pub /home/rsync/.ssh/authorized_keys chmod 600 /home/rsync/.ssh/authorized_keys
重启SSH服务 [root@A ~]# /etc/init.d/sshd restart [root@B ~]# /etc/init.d/sshd restart
5、inotify_tools的使用 1、确定inotifywait的位置 2、inotifywait的常见使用方法
/usr/bin/inotifywait -mrq -e modify,delete,create,attrib 命令解释: -m 是保持一直监听 -r 是递归查看目录 -q 是打印出事件 -e create,move,delete,modify,attrib 是指 “监听 创建 移动 删除 写入 权限” 事件
6、服务器A上创建实时监控备份脚本inotify.ssh
#!/bin/sh SRC=/usr/local/mysql/binlog/ DST=[email protected]:/home/rsync1/test /usr/bin/inotifywait -mrq -e modify,delete,create,attrib ${SRC} | while read D E F do /usr/bin/rsync -ahqzt --delete $SRC $DST done
命令解释: SRC:监控的目录() DST:备份的目录 while read D E F:inotifywait 命令产生三个返回值,分别是“日期,时间,文件” 这3个返回值会做为参数传给read,因此脚本中的“while read D E F” 写法细化了返回值。
rsync命令解释: /usr/bin/rsync -ahqzt --delete $SRC $DST -a 存档模式 -h 保存硬连接 -q 制止非错误信息 -z 压缩文件数据在传输 -t 维护修改时间 -delete 删除于多余文件
7、脚本的运行
服务器A:
修改执行权限:chmod +x inotify.sh 在rsync用户模式下运行该脚本(ssh-key是rsync用户建立的): su - rsync [rsync@A sbin]$ ./inotify_rsync.sh & #在后台运行
此次在服务器A的/usr/local/mysql/binlog/#在该目录下,建立文件和目录,可以实时备份到目标位置
注意: 1、备份用户rsync有没有读取/usr/local/mysql/binlog/目录的权限,不然备份失败 2、建议修改mysql-bin的存储目录,如下所示 log-bin=/usr/local/mysql/binlog/mysql-bin #打开日志(主机需要打开),这个mysql-bin也可以自定义,这里也可以加上路径,如:/usr/local/mysql/binlog/mysql-bin |