十三、rsync+inotify的使用

简介:

  rsync(remote synchronize)是一个远程数据同步工具,可以通过LAN/WAN快速同步多台主机之间的文件。也可以使用rsync同步本地磁盘中的不同目录。在使用rsync进行远程同步时,可以使用两种方式:远程shell方式和C/S方式。无论本地同步目录还是远程同步数据,首次运行时将会把全部文件复制一次,以后再运行时将只复制有变化的文件或文件的变化部分。

  实施备份时有两种情况:

1、需要保留备份历史归档,在备份时保留历史的备份归档,是为了在系统出现错误后能恢复到当前的状态,这可以使用完全备份和增量备份来完成。

  可以使用tar命令保存归档文件

  为了提高备份效率,也可以使用rsync结合tar来完成

2、无需保留备份历史归档,则只需要备份系统最‘新鲜’的状态,这可以使用rsync同步来完成,此时通常称为镜像。镜像可以分为两种:

  被镜像的目录在各个主机上保存相同的位置,此时一般是为了实施负载均衡而对多个主机进行同步镜像;

  被镜像的目录在哥哥主机上不保持相同的位置。

  

  • rsync命令

 rsync是一个功能强大的工具,其命令也有很多功能选项,其命令格式为:

本地使用:
    Local:  rsync [OPTION...] SRC... [DEST]
    
远程shell模式,此时可以利用ssh协议承载其数据传输过程:
    Pull: rsync [OPTION...] [USER@]HOST:SRC... [DEST]
    Push: rsync [OPTION...] SRC... [USER@]HOST:DEST
    
服务模式,此时rsync工作为守护进程,能接收客户端的数据同步请求
    Pull: rsync [OPTION...] [USER@]HOST::SRC... [DEST]
          rsync [OPTION...] rsync://[USER@]HOST[:PORT]/SRC... [DEST]
    Push: rsync [OPTION...] SRC... [USER@]HOST::DEST
          rsync [OPTION...] SRC... rsync://[USER@]HOST[:PORT]/DEST

其中:

  SRC: 要复制的源位置

  DEST:复制目标位置

  若本地登录用户与远程主机上的用户一致,可以省略USER@

  使用远程shell同步时,主机名与资源名之间用':'作为分隔符

  使用rsync服务器同步时,主机名与资源名之间用'::'作为分隔符

  pull,'拉'是指从远程主机复制文件到本地主机

  push,'推'是指从本地主机复制文件到远程主机

  当进行'拉'复制时,若指定一个SRC且省略DEST,则只列出资源而不复制

注意:rsync命令中,如果源路径是目录,且给复制路径时末尾有/,则会复制目录中的内容,而非目录本身;如果末尾没有/,则会同步目录本身及目录中的所有文件;目标路径末尾是否有/无关紧要。

rsync常用选项:

-n: 同步测试,不执行真正的同步过程;

-v: --verbose详细输出模式

-q: --quiet,静默模式

-c: --checksum开启校验功能

-r: --recursive递归复制;

-a: --archives归档保留文件的原有属性

-p: --perms 保留文件的权限

-t: --times 保留文件的时间戳

-l: --links 保留文件的符号链接 

-g: --group 保留文件的属组

-o: --owner 保留文件的属主

-D:--devices 保留设备文件

-e ssh: 表示使用ssh协议作承载

-z: 对文件压缩后传输

--progress:显示进度条

--stats: 显示如何执行压缩和传输

--delete:删除那些接收端还保留,而发送端已经不存在的数据

  • rsync的基本使用

本地磁盘同步数据:

[root@localhost ~]# ls /home/                         #本地磁盘数据
samba-4.6.5  samba-4.6.5.tar.gz
[root@localhost ~]# rsync -a --delete /home /backups/ #将整个/home目录复制到目标目录
[root@localhost ~]# ls /backups/
home
[root@localhost ~]# rsync -a --delete /home/ /backups/#将/home目录中内容复制到目标目录
[root@localhost ~]# ls /backups/
samba-4.6.5  samba-4.6.5.tar.gz

使用基于ssh的rsync远程同步数据:

[root@localhost ~]# rsync /etc/hosts  192.168.191.129:/etc/hosts   #执行推同步
root@192.168.191.129's password: 
[root@localhost ~]# rsync 192.168.191.129:/etc/hosts /etc/hosts    #执行拉同步
root@192.168.191.129's password:

13.2、配置rsync以daemon方式运行

1、设定rsync服务器端

 1) 安装并启动xinetd

[root@localhost ~]# yum -y install xinetd rsync

  2) 为rsync服务提供配置文件/etc/rsyncd.conf

[root@localhost ~]# vim /etc/rsyncd.conf
# Global Settings
uid = nobody        #以什么身份运行进程
gid = nobody
use chroot = no
max connections = 10
strict modes = yes
pid file = /var/run/rsyncd.pid
log file = /var/log/rsyncd.log
list = yes
# Directory to be synced
[synced_name]
path = /home/
ignore errors = yes
read only = no
write only = no
list = false
uid = root                           #以什么身份获取文件
gid = root
auth users = username
secrets file = /etc/rsyncd.passwd    #用户账号验证文件
hosts allow = 192.168.191.129 
hosts deny = *

权限说明:

 1、二者都不出现时,默认为允许访问;

 2、只出现hosts allow: 白名单;但没有被匹配到的主机默认处理,允许;

 3、只出现hosts deny:黑名单;出现在名单中的都被拒绝;

 4、二者同时出现:先检查hosts allow,匹配到就allow,否则,检查hosts deny,匹配则拒绝;如二者均无匹配,则由默认规则处理,即为允许;

  3) 配置密码文件/etc/rsyncd.passwd

   文件格式(明文):username:password  (文件权限要设置为600)

[root@localhost ~]# vim /etc/rsyncd.passwd
mylinux:123
[root@localhost ~]# chmod 600 /etc/rsyncd.passwd

  4) 配置服务能够启动

[root@localhost ~]# chkconfig rsync on
[root@localhost ~]# service xinetd start     #监听端口tcp/873
Starting xinetd: [  OK  ]
[root@localhost ~]# setenforce 0             #关闭selinux,很关键

2、在客户端做测试

[root@localhost ~]# rsync --list-only rsync://mylinux@192.168.191.128/home   #查看列表
Password: 
drwxr-xr-x        4096 2017/06/15 18:06:02 .
-rwxr-xr-x    21111639 2017/06/06 15:50:37 samba-4.6.5.tar.gz
drwxr-xr-x        4096 2017/06/15 18:06:02 mylinux
drwxr-xr-x        4096 2017/06/13 17:28:15 samba-4.6.5

[root@localhost ~]# rsync -avzP --delete mylinux@192.168.191.128::home /backups/
Password:                                      #简单同步,不保存历史文档
receiving incremental file list
./
mylinux/
mylinux/.bash_logout
          18 100%   17.58kB/s    0:00:00 (xfer#1, to-check=1013/1018)
mylinux/.bash_profile
         176 100%   85.94kB/s    0:00:00 (xfer#2, to-check=1012/1018)
mylinux/.bashrc
         124 100%   60.55kB/s    0:00:00 (xfer#3, to-check=1011/1018)

sent 45978 bytes  received 453928 bytes  199962.40 bytes/sec
total size is 470170720  speedup is 940.52
[root@localhost ~]# ls /backups/                #备份的文件
mylinux  samba-4.6.5  samba-4.6.5.tar.gz

13.3、inotify简单介绍

  inotify是linux内核特性,它监控文件系统并及时项专门的应用程序发出相关事件的警告。如:读、写、删除、备份等。其操作工具为inotify-tools。要使用 inotify,必须具备一台带有2.6.13 或更新内核的 Linux 机器(以前的 Linux 内核版本使用更低级的文件监控器dnotify)。

[root@localhost ~]# uname -a                         #查看内核版本
Linux contos 2.6.32-431.el6.x86_64 #1 SMP Fri Nov 22 03:15:09 UTC 2013 x86_64 x86_64 x86_64 GNU/Linux
[root@localhost ~]# ls -l /proc/sys/fs/inotify/      #查看是否支持inotify
total 0
-rw-r--r-- 1 root root 0 Jun 15 21:09 max_queued_events  #inotify队列最大长度
-rw-r--r-- 1 root root 0 Jun 15 21:09 max_user_instances #每个用户创建inotify实例最大值
-rw-r--r-- 1 root root 0 Jun 15 21:09 max_user_watches   #要同步的文件包含的目录数

[root@localhost home]# wget                                     #下载 inotify-tools源码包
[root@localhost home]#tar xf inotify-tools-3.14.tar.gz 
[root@localhost home]#cd inotify-tools-3.14
[root@localhost inotify-tools-3.14]./configure --prefix=/usr/local/inotify-tools
[root@localhost inotify-tools-3.14]make && make install

  在inotify-tools工具包中有两个工具inotifywait和inotifywatch。

  inotifywait:在被监控的文件系统或目录上等待特定文件系统事件(open、close、delete等)。执行后处于阻塞状态,适合脚本中使用。

  inotifywatch:收集被监视文件系统使用时数据统计、指文件系统事件发出次数统计。

inotifywait  [-cmrq]  [-e <event> ] [-t <seconds> ] [--format <fmt> ][--timefmt <fmt> ] <file>     #inotifywait语法格式

常用参数:

--timefmt 时间格式  

  %y年 %m月 %d日 %H小时 %M分钟  

--format 输出格式  

  %T时间 %w路径 %f文件名 %e状态  

-m 始终保持监听状态,默认触发事件即退出。  

-r 递归查询目录  

-q 打印出监控事件  

-e 定义监控的事件,可用参数:  

open 打开文件  

access 访问文件  

modify 修改文件  

delete 删除文件  

create 新建文件  

attrb  属性变更 

Options:
        -h|--help       Show this help text.
        @<file>         Exclude the specified file from being watched.
        --exclude <pattern>
                        Exclude all events on files matching the
                        extended regular expression <pattern>.
        --excludei <pattern>
                        Like --exclude but case insensitive.
        -m|--monitor    Keep listening for events forever.  Without
                        this option, inotifywait will exit after one
                        event is received.
        -d|--daemon     Same as --monitor, except run in the background
                        logging events to a file specified by --outfile.
                        Implies --syslog.
        -r|--recursive  Watch directories recursively.
        --fromfile <file>
                        Read files to watch from <file> or `-' for stdin.
        -o|--outfile <file>
                        Print events to <file> rather than stdout.
        -s|--syslog     Send errors to syslog rather than stderr.
        -q|--quiet      Print less (only print events).
        -qq             Print nothing (not even events).
        --format <fmt>  Print using a specified printf-like format
                        string; read the man page for more details.
        --timefmt <fmt> strftime-compatible format string for use with
                        %T in --format string.
        -c|--csv        Print events in CSV format.
        -t|--timeout <seconds>
                        When listening for a single event, time out after
                        waiting for an event for <seconds> seconds.
                        If <seconds> is 0, inotifywait will never time out.
        -e|--event <event1> [ -e|--event <event2> ... ]
                Listen for specific event(s).  If omitted, all events are 
                listened for.
Exit status:
        0  -  An event you asked to watch for was received.
        1  -  An event you did not ask to watch for was received
              (usually delete_self or unmount), or some error occurred.
        2  -  The --timeout option was given and no events occurred
              in the specified interval of time.
Events:
        access          file or directory contents were read
        modify          file or directory contents were written
        attrib          file or directory attributes changed
        close_write     file or directory closed, after being opened in
                        writeable mode
        close_nowrite   file or directory closed, after being opened in
                        read-only mode
        close           file or directory closed, regardless of read/write mode
        open            file or directory opened
        moved_to        file or directory moved to watched directory
        moved_from      file or directory moved from watched directory
        move            file or directory moved to or from watched directory
        create          file or directory created within watched directory
        delete          file or directory deleted within watched directory
        delete_self     file or directory was deleted
        unmount         file system containing file or directory unmounted
inotifywatch [ options ] file1 [ file2 ] [ ... ]   #inotifywatch语法格式
Options:
        -h|--help       Show this help text.
        -v|--verbose    Be verbose.
        @<file>         Exclude the specified file from being watched.
        --fromfile <file>
                Read files to watch from <file> or `-' for stdin.
        --exclude <pattern>
                Exclude all events on files matching the extended regular
                expression <pattern>.
        --excludei <pattern>
                Like --exclude but case insensitive.
        -z|--zero
                In the final table of results, output rows and columns even
                if they consist only of zeros (the default is to not output
                these rows and columns).
        -r|--recursive  Watch directories recursively.
        -t|--timeout <seconds>
                Listen only for specified amount of time in seconds; if
                omitted or 0, inotifywatch will execute until receiving an
                interrupt signal.
        -e|--event <event1> [ -e|--event <event2> ... ]
                Listen for specific event(s).  If omitted, all events are 
                listened for.
        -a|--ascending <event>
                Sort ascending by a particular event, or `total'.
        -d|--descending <event>
                Sort descending by a particular event, or `total'.
Exit status:
        0  -  Exited normally.
        1  -  Some error occurred.
Events:
        access          file or directory contents were read
        modify          file or directory contents were written
        attrib          file or directory attributes changed
        close_write     file or directory closed, after being opened in
                        writeable mode
        close_nowrite   file or directory closed, after being opened in
                        read-only mode
        close           file or directory closed, regardless of read/write mode
        open            file or directory opened
        moved_to        file or directory moved to watched directory
        moved_from      file or directory moved from watched directory
        move            file or directory moved to or from watched directory
        create          file or directory created within watched directory
        delete          file or directory deleted within watched directory
        delete_self     file or directory was deleted
        unmount         file system containing file or directory unmounted




本文转自 梦想成大牛 51CTO博客,原文链接:http://blog.51cto.com/yinsuifeng/1937023,如需转载请自行联系原作者

相关文章
|
1天前
|
人工智能 自然语言处理 JavaScript
2026年Windows+Ollama本地部署OpenClaw保姆级教程:本地AI Agent+阿里云上快速搭建
2026年OpenClaw凭借本地部署、私有化运行的特性,成为打造个人智能体的核心工具,而Ollama作为轻量级本地大模型管理工具,能让OpenClaw摆脱对云端大模型的依赖,实现**本地推理、数据不泄露、全流程私有化**的智能体验。本文基于Windows 11系统,从硬件环境准备、Ollama安装与模型定制、OpenClaw部署配置、技能扩展到常见问题排查,打造保姆级本地部署教程,同时补充阿里云OpenClaw(Clawdbot)快速部署步骤,兼顾本地私有化需求与云端7×24小时运行需求,文中所有代码命令均可直接复制执行,确保零基础用户也能快速搭建属于自己的本地智能体。
2836 12
|
12天前
|
人工智能 自然语言处理 监控
OpenClaw skills重构量化交易逻辑:部署+AI全自动炒股指南(2026终极版)
2026年,AI Agent领域最震撼的突破来自OpenClaw(原Clawdbot)——这个能自主规划、执行任务的智能体,用50美元启动资金创造了48小时滚雪球至2980美元的奇迹,收益率高达5860%。其核心逻辑堪称教科书级:每10分钟扫描Polymarket近千个预测市场,借助Claude API深度推理,交叉验证NOAA天气数据、体育伤病报告、加密货币链上情绪等多维度信息,捕捉8%以上的定价偏差,再通过凯利准则将单仓位严格控制在总资金6%以内,实现低风险高频套利。
6421 57
|
8天前
|
存储 人工智能 负载均衡
阿里云OpenClaw多Agent实战宝典:从极速部署到AI团队搭建,一个人=一支高效军团
在AI自动化时代,单一Agent的“全能模式”早已无法满足复杂任务需求——记忆臃肿导致响应迟缓、上下文污染引发逻辑冲突、无关信息加载造成Token浪费,这些痛点让OpenClaw的潜力大打折扣。而多Agent架构的出现,彻底改变了这一现状:通过“单Gateway+多分身”模式,让一个Bot在不同场景下切换独立“大脑”,如同组建一支分工明确的AI团队,实现创意、写作、编码、数据分析等任务的高效协同。
2848 27
|
30天前
|
人工智能 自然语言处理 Shell
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
本教程指导用户在开源AI助手Clawdbot中集成阿里云百炼API,涵盖安装Clawdbot、获取百炼API Key、配置环境变量与模型参数、验证调用等完整流程,支持Qwen3-max thinking (Qwen3-Max-2026-01-23)/Qwen - Plus等主流模型,助力本地化智能自动化。
43530 157
🦞 如何在 OpenClaw (Clawdbot/Moltbot) 配置阿里云百炼 API
|
4天前
|
人工智能 JavaScript API
2026年Windows系统本地部署OpenClaw指南:附阿里云简易部署OpenClaw方案,零技术基础也能玩转AI助手
在AI办公自动化全面普及的2026年,OpenClaw(原Clawdbot、Moltbot)凭借“自然语言指令操控、多任务自动化执行、多工具无缝集成”的核心优势,成为个人与轻量办公群体打造专属AI助手的首选。它彻底打破了传统AI“只会对话不会执行”的局限——“手”可读写本地文件、执行代码、操控命令行,“脚”能联网搜索、访问网页并分析内容,“大脑”则可灵活接入通义千问、OpenAI等云端API,或利用本地GPU运行模型,真正实现“聊天框里办大事”。
992 2
|
2天前
|
人工智能 JSON JavaScript
手把手教你用 OpenClaw + 飞书,打造专属 AI 机器人
手把手教你用 OpenClaw(v2026.2.22-2)+ 飞书,10分钟零代码搭建专属AI机器人!内置飞书插件,无需额外安装;支持Claude等主流模型,命令行一键配置。告别复杂开发,像聊同事一样自然对话。
1016 5
手把手教你用 OpenClaw + 飞书,打造专属 AI 机器人