rsync详解之exclude排除文件
在使用rsync工具进行数据同步时,需要排除掉一些目录或者文件该如何做呢?其实很简单,rsync提供了一个--exclude的选项,只需要在命令行排除掉这些内容即可。
例:将远程源服务器/home/ 目录同步到本地/home 目录,但需要将源服务器/home/testuser这个目录排除掉。
my-host:~ # rsync -avP --delete --exclude 'testuser' root@192.168.57.178:/home/ /home
注意:
1、这个路径必须是一个相对路径,不能是绝对路径。不可写为 --exclude '/testuser'。
2、系统会把文件和文件夹一视同仁,如果testuser是一个文件,同样不会复制。
3、如果想避开复制testuser里面的内容,可以这么写--exclude 'testuser/file1',
4、可以使用通配符 避开不想复制的内容
比如--exclude “fire*”
那么fire打头的文件或者文件夹全部不会被复制
从某个文件中读取要排除的内容
如果想要避开复制的文件过多,可以这么写
--exclude-from=/exclude.list
exclude.list 是一个文件,保存要排除的目录或文件,放置的位置是绝对路径的/exclude.list ,为了避免出问题,最好设置为绝对路径。
里面的内容一定要写为相对路径
如,我想同步/home目录,要排除几百个子目录
my-host:~ # rsync -avP --delete --exclude-from='/exclude.list' root@192.168.57.178:/home/ /home my-host:~ # head /exclude.list ftpboot/biget/book/catalogdata/* ftpboot/biget/catalogtree/* ftpboot/baidusearch/book/meta/* ftpboot/mreadsearch/book/meta/* ftpboot/mreadMobile/book/meta/* ftpboot/searchengine/book/* 略……
写为--exclude-from或者--exclude-from=都可以
我这里是想同步目录忽略目录下的内容所以 exclude.list 用了类似这种结构 ftpboot/biget/book/catalogdata/*
rsync+ssh非交互登录同步数据
前面的方法在同步开始前需要输入源主机用户密码,在传输少量文件时没有问题,但有时同步的数据量比较大,也许需要好几天,总不能开这远程窗口等待执行完成吧。或者我们需要配置定时任务进行同步,这时ssh登录交互的方式不太适合。
有两种方法可以解决此问题。
一、配置两台主机ssh免密互信
二、使用sshpass免交互的ssh登录工具
1、在本机上安装sshpass,centos的用户直接通过下面的命令安装:
yum install sshpass
或者在 https://sourceforge.net/projects/sshpass/files/latest/download 下载源码,通过编译的方式安装:
tar zxvf sshpass-1.06.tar.gz cd sshpass-1.06 ./configure make install
2、在本机上通过rsync传送远程主机文件到本机,运行下面的命令:
sshpass -p '123456' rsync -avP --delete --exclude-from='/exclude.list' -e 'ssh -p 19222' root@192.168.57.178:/home/ /home
sshpass man 手册中还列举了两个示例
EXAMPLES
Run rsync over SSH using password authentication, passing the password on the command line:
rsync --rsh='sshpass -p 12345 ssh -l test' host.example.com:path
To do the same from a bourne shell script in a marginally less exposed way:
SSHPASS=12345 rsync --rsh='sshpass -e ssh -l test' host.example.com:path
其中:
-p: 后面接远程主机的登录密码
'ssh -p 19222' :表示通过ssh连接,ssh服务使用的19222端口
实现了免密登录,就可以将同步命令放到后台,然后关掉窗口放心地做其他事了,也不用担心登录shell断开导致同步失败。
nohup sshpass -p 'passwd' rsync -avP --delete --exclude-from='/exclude.list' -e 'ssh -p 19222' root@192.168.57.178:/home/ /home &