rsync同步文件
更新日期:
工作中有不少情况会遇到需要同步文件的情况,这里就记录下同步的方法。
例如我们要把A机器(192.168.0.101)/home/xxx/test目录下所有文件和目录同步到B机器(192.168.0.102)/home/xxx/test目录下:
1.ssh无密码登陆
首先要实现A机器到B机器的无密码登陆,在A机器上执行:1
2ssh-keygen -t rsa
ssh-copy-id -i ~/.ssh/id_rsa.pub xxx@192.168.0.102
2.安装rsync
A机器安装rsync,可直接执行yum install rsync安装。
3.rsync同步
1 | rsync -ravz --delete --progress --include="*.h" --include="*.cpp" --include="*.proto" --exclude="*.*" --exclude="bin/*" --exclude="Makefile*" -e ssh /home/xxx/test/ xxx@192.168.0.102:/home/xxx/test/ |
–exclude=”*.*“表示过滤掉所有带后缀的文件 –exclude=”bin/*“表示过滤掉bin目录下的所有文件和目录 –exclude=”Makefile*“表示过滤掉所有Makefile开头的文件和目录
–include=”*.h” –include=”*.cpp” –include=”*.proto” 表示只同步以.h .cpp .proto为后缀的文件
这样就把A test目录下及其所有的子目录下的所有.h .cpp .proto为后缀的文件同步到了B机器上。
4.安装inotify-tools
如果想实现文件的实时同步需要安装inotify-tools,它可以监控文件的变化,1
2
3
4
5
6git clone https://github.com/rvoicilas/inotify-tools.git
cd inotify-tools
./autogen.sh
#yum install autoconf automake libtool
./configure
make&&make install
然后可运行以下命令监控目录:1
inotifywait -mrq --timefmt '%Y%m%d%H%M%S' --format '%T,%w%f,%e' -e modify,delete,create,attrib /home/xxx/test/
5.inotifywait+rsync实现脚本实时同步
1 | #!/bin/bash |
执行这个脚本就可以实时把文件从A机器同步到B机器了。