rsync: 一款开源备份工具; 实现不同主机间镜像同步整个目录树; 支持增量备份, 权限, 压缩等
rsync 角色
发起端: 负责发起 rsync 同步, 操作客户机 (相当于 C 端)
备份源: 负责响应 rsync 的请求的服务器 (相当于 S 端)
同步的方向
上行同步 (上传): 备份源提供文档的目标位置 (date 在发起端), 发起端使用用户必须对目录有写入权限
下行同步 (下载): 备份源负责提供文档原始位置 (date 在备份源), 发起端使用用户只需对 data 有读取权限即可
搭建 rsync 备份源
- vim /etc/rsyncd.db
- hehe:123 // 用户名: 密码
- vim /etc/rsyncd.conf
- uid = nobody // 运行用户
- gid = nobody // 运行组
- use chroot = yes // 用户禁锢到访问目录
- address = 192.168.1.10 // 监听 IP
- port 873 // 监听端口
- log file = /var/log/rsyncd.log // 日志文件位置
- pid file = /var/run/rsyncd.pid //PID 运行文件位置
- hosts allow = 192.168.1.0/24 // 运行同步的网段
- [data] // 同步名
- path = /data // 同步的目录
- comment = Document Root // 描述
- read only = no
- write = yes // 用户可写
- dont compress = *.gz *.bz2 *.tgz *.zip *.rar *.z // 同步时不需压缩的格式
- auth users = hehe // 认证用户
- secrets file = /etc/rsyncd.db // 用户帐号文件位置
- chmod 600 /etc/rsync.db
- mkdir /data && chmod 777 /data
- rsync --daemon // 独立模式运行 rsync 服务; 停止 rsync(killall rsync && rm -rf /var/run/rsyncd.pid)
client 同步 (注意将 write = yes 增加)
下行: rsync [ 选项 ] 远程目录 本地目录
上行: rsync [ 选项 ] 本地目录 远程同步名
选项 - a: 提供归档和属性信息 - v: 显示详细信息 - z: 压缩 - H: 保持硬链接 - u: 可实现增量备份
- mkdir /a
- rsync -avzH --delete rsync://hehe@192.168.1.10/data//a/// 将备份源中的数据下载同步到当前位置
- rsync -avzH --delete hehe@192.168.1.10::data /a/
两条命令任选其一
- rsync -avzH --delete /a/ rsync://hehe@192.168.1.10/data // 将发起端的数据上传同步到备份源; 用户在备份源必须有写入权限
- rsync -avzH --delete /a/ hehe@192.168.1.10::data
两条命令任选其一
计划任务实现定时下行同步
- vim /etc/profile
- export RSYNC_PASSWORD=123 // 将 rsync 密码加入环境变量
- source /etc/profile
- crontab -e
- * */4 * * */usr/bin/rsync -avzHu --delete rsync://hehe@192.168.1.10/data /a // 定时下行同步
- * */4 * * */usr/bin/rsync -avzHu --delete /a rsync://hehe@192.168.1.10/data // 定时上行同步
rsync+inofity: 注意用于上行实时同步 (以下操作全在客户端)
安装 inotify-tools
- tar zxvf inotify-tools-*.tar.gz -C /usr/src/
- cd /usr/src/inotify-tools-*/
- ./configure && make && make install
inotify 的使用
- vim /etc/sysctl.conf
- fs.inotify.max_queued_events = 16384 ## 监控事件队列数
- fs.inotify.max_user_instances = 1024 ## 监控实例数
- fs.inotify.max_user_watches = 1048576 ## 监控的文件数量
- sysctl -p
- vim rsync_inotify.sh ## 实时同步脚本
- #!/bin/bash
- RSYNC="rsync -avzHu --delete /a/ rsync://hehe@192.168.1.10/data"
- INT_CMD="inotifywait -mrq -e modify,create,move,delete,attrib /a"
- export RSYNC_PASSWORD=123 // 可解决 rsync 同步时, 无需输入密码
- $INT_CMD | while read DIRECOTRY EVENT FILE;do
- $RSYNC 1>/dev/null 2>/var/log/rsync_err.log
- done
- chmod +x rsync_inotify.sh // 给予脚本执行权限
- rsync_inotify.sh & // 启动脚本
来源: http://www.bubuko.com/infodetail-2755560.html