背景
在创建集群时,经常需要同时在多个机器上创建相同的文件,如果手动创建就很麻烦。于是就使用 rsync 工具,在一个机器上创建完成后,将它同步到其他的机器。一般 rsync 使用 ssh 协议,但是需要配置 ssh 服务,创建公钥私钥等,比较麻烦。这篇文章记录如何使用 rsync 协议同步文件,方便自己以后查询。
注意:只适用于测试环境。 比如我的测试环境系统没有ssh,默认root权限。对安全性也没有任何要求,只想在各个机器间同步文件。
配置服务
- 配置每台机器上的 rsync 服务。创建 rsync 配置文件
vi /etc/rsyncd.conf
内容如下:
pid file = /var/run/rsyncd.pid
log file = /var/log/rsyncd.log
[share]
path = /
uid = root
gid = root
read only = no
dont compress = *.gz *.bz2 *.zip
auth users = test
secrets file = /etc/rsyncd.secrets
参数 path 直接指定为根目录。
- 创建用户密码文件。
vi /etc/rsyncd.secrets
内容如下:
test:1
用户名为 test ,密码为 1.
- 设置文件权限。
chmod 600 /etc/rsyncd.secrets
- 启动服务
sed -i 's/RSYNC_ENABLE=false/RSYNC_ENABLE=true/g' /etc/default/rsync
service rsync start
同步文件
常见用法:
a. 只同步/root目录下的某个文件到目标主机 1.1.1.2 /root 目录
rsync -av /root/123 [email protected]::share/root
提示输入密码,输入 1 就行。
b. 同步文件夹 /root/中所有的文件到目标主机 1.1.1.2 /root 目录
rsync -av /root/ [email protected]::share/root
c. 确保目标主机 1.1.1.2 /root 目录和主机/root 目录完全一致。比如我删除了几个文件,也想要其他主机删除这个文件,那么就添加 delete 参数。
rsync -av --delete /root/ [email protected]::share/root
shell脚本
#!/bin/bash
touch /etc/rsyncd.conf
cat << EOF > /etc/rsyncd.conf
pid file = /var/run/rsyncd.pid
log file = /var/log/rsyncd.log
[share]
path = /
uid = root
gid = root
read only = no
dont compress = *.gz *.bz2 *.zip
auth users = test
secrets file = /etc/rsyncd.secrets
EOF
touch /etc/rsyncd.secrets
echo "test:1" > /etc/rsyncd.secrets
chmod 600 /etc/rsyncd.secrets
sed -i 's/RSYNC_ENABLE=false/RSYNC_ENABLE=true/g' /etc/default/rsync
service rsync start