Centos7利用rsync实现文件同步




测试环境:



CentOS 7.4 Rsync服务端:192.168.99.112
CentOS 7.4 Rsync客户端:192.168.99.136



 

第一种方式:rsync通过ssh方式同步

1、Rsync服务端和客户端都需要安装rsync

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

 

2、使用

前提:需知道远程服务器开启ssh端口和账号密码

A、推文件: 

[root@localhost tmp]# rsync -av /etc/passwd  192.168.204.168:/tmp/passwd.txt

Centos7利用rsync实现文件同步_CentOS

B、拉文件

[root@localhost tmp]# rsync -av  192.168.204.168:/tmp/passwd.txt  /tmp/test.txt

 

Centos7利用rsync实现文件同步_linux_02

#指定ssh 端口 

[root@localhost tmp]# rsync -av -e "ssh -p 22" 192.168.204.168:/tmp/passwd.txt  /tmp/a.txt

Centos7利用rsync实现文件同步_linux_03

第二种方式:rsync通过服务的方式同步

服务端配置:

1、编辑配置文件/etc/rsyncd.conf



motd file = /etc/rsyncd.motd
transfer logging = yes
log file = /var/log/rsyncd.log
port = 873
address = 192.168.204.130
uid = nobody
gid = nobody
use chroot = no
read only = no
max connections = 10
[common]
comment = rsync info
path = /tmp
ignore errors
auth users = admin
secrets file = /etc/rsyncd.secrets
hosts allow = 192.168.204.0/255.255.255.0
hosts deny = *
list = false



2、创建用户密码文件

echo "admin:123456" > /etc/rsyncd.secrets

chmod 600 /etc/rsyncd.secrets

3、创建提示信息文件:

 echo  "rsync  info"  >  /etc/rsyncd.motd

4、启动服务:

rsync  --daemon
echo  "rsync  --daemon"  >>  /etc/rc.local

 

 客户端配置:

创建密码文件(免密码输入):

echo  "123456"  >  /root/passwd
chmod  600  /root/passwd

 

拉取:

rsync -avz --password-file=/root/passwd  admin@192.168.204.130::common /tmp 

Centos7利用rsync实现文件同步_linux_04

推送:

rsync -avz --password-file=/root/passwd /tmp/ admin@192.168.204.130::common

 

Centos7利用rsync实现文件同步_服务端_05

 

定时任务:

1、新建一个rsync.sh文件,在文件中写入执行同步的命令:

rsync -avz --password-file=/root/passwd  admin@192.168.204.130::common /tmp  >/dev/null 2>&1

2、chmod 755  rsync.sh

3、执行命令:crontab -e



在定时文件中写入定时执行任务,实例如下:
       * * * * * /home/rsync.sh                 每分钟执行一次同步脚本;
        0 * * * * /home/rsync.sh                 每小时执行一次同步脚本;
        0 0 * * * /home/rsync.sh                 每天零点执行一次同步脚本; 
        0 9,18 * * * /home/rsync.sh            每天的9AM和6PM执行一次同步脚本;