关于linux:linux下使用rsync同步目录

10次阅读

共计 1768 个字符,预计需要花费 5 分钟才能阅读完成。

本文形容了 linux 下应用 rsync 单向同步两个机器目录的问题。应用 rsync 同步后能够放弃目录的一致性(含删除操作)。

数据同步形式

1、从主机拉数据

备机上启动的流程

同步命令:

rsync -avzP –delete root@{remoteHost}:{remoteDir} {localDir}

参数阐明:

-a 参数,相当于 -rlptgoD(-r 是递归 -l 是链接文件,意思是拷贝链接文件;-p 示意放弃文件原有权限;-t 放弃文件原有工夫;-g 放弃文件原有用户组;-o 放弃文件原有属主;-D 相当于块设施文件);-z 传输时压缩;-P 传输进度;-v 传输时的进度等信息;

示例:

rsync -avzP –delete root@192.168.1.100:/tmp/rtest1 /tmp/

2、向备机推数据

主机上启动的流程

同步命令:

rsync -avzP –delete {localDir} root@{remoteHost}:{remoteDir}

示例:

rsync -avzP –delete /tmp/rtest1 root@192.168.1.101:/tmp/

主动同步配置

形容同步时不输出明码的配置的办法。

1、应用 ssh key

该办法能够间接应用 rsync 命令进行同步,同步过程中无需输出明码。

在主机上产生 ssh key :

ssh-keygen -t rsa

在备机上退出 pubkey

ssh-copy-id -i ~/.ssh/id_rsa.pub root@192.168.1.101

或者手动增加:

在主机上执行以下命令获取 pubkey:

cat ~/.ssh/id_rsa.pub

在备机上退出 key 内容:

vi ~/.ssh/authorized_keys

应用 pexpect 主动输出明码

示例代码如下:

*#!/usr/bin/env python# –– coding: utf-8 -*-import pexpectimport timeimport tracebackdef doRsync(user,passwd,ip,srcDir,dstDir,timeout=3600): cmd = “rsync -azPq –delete {srcDir} {rUser}@{rHost}:{dstDir}”.format(rUser = user,rHost=ip,srcDir=srcDir,dstDir=dstDir) try: ssh = pexpect.spawn(cmd,timeout=timeout) print cmd i = ssh.expect([‘password:’, ‘continue connecting (yes/no)?’], timeout=5) if i == 0 : ssh.sendline(passwd) elif i == 1: ssh.sendline(‘yes’) ssh.expect(‘password: ‘) ssh.sendline(passwd) ssh.read() ssh.close() except : #print traceback.format_exc() passif name == ‘main’: doRsync(“root”,”123456″,”192.168.1.101″,”/tmp/rtest1″,”/tmp”)

下面是应用 python 实现的代码,大家可依据状况用其它语言实现该性能。

其它

1、rsync 在执行过程中被 kill 掉会怎么样;

It is safe to kill an rsync process and run the whole thing again; it will continue where it left off. It may be a little inefficient, particularly if you haven’t passed –partial (included in -P), because rsync will check all files again and process the file it was interrupted on from scratch.**

rsync 被 kill 掉是平安的,下次启动时还能够失常工作。

2、rsync 不能指定时间段;

1)该站长博客问题能够通过 kill 来解决

2)或者应用 pexpect 的 timeout 参数来管制

3)能够先通过 find 查找过滤出文件夹的名字,而后应用 rsync 进行同步 这个能够依据现有业务的特色进行,比方:

正文完
 0