利用sshfs将2台centos服务器实时同步数据

需求:

两台服务器(A,B)要求,A里的数据通过sshfs实时同步到B上

 

假设两台服务器的ip分别是 :

A: 192.168.1.100 (源服务器,数据源的目录为/home/data/)

B: 192.168.1.101 (目标服务器,把数据同步到的目录:/home/sync_dir/)

 

1、安装 sshfs(A、B服务器都需要安装):

yum install -y epel-release fuse-sshfs (通过yum安装)

 

rpm -Uvh --force --nodeps fuse-sshfs-2.4-1.el6.x86_64.rpm (离线安装)

rpm -Uvh --force --nodeps epel-release-6-8.noarch.rpm

 

2、挂载命令:

在B上通过同步工具将A服务器上的目录挂载到B上指定的目录上;

例:将A上的 /home/data/ 同步到B上的 /home/sync_dir/,命令如下(再B服务器上执行):

sshfs -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 root@192.168.1.100:/home/data/ /home/sync_dir/

 

3、设置自动挂载(当服务器重启时会自动触发同步机制):

在B服务器执行命令

cd /root/.ssh/   【root用户就在root目录下的.ssh目录】

cd /home/用户/.ssh/   【普通用户就是在家目录下的.ssh目录】

 

1)B服务器生成私钥和公钥

ssh-keygen -t dsa  一路回车即可

id_dsa        私钥(钥匙)

id_dsa.pub      公钥(锁)

 

2)拷贝B服务器的公钥给A服务器

ssh-copy-id -i id_dsa.pub root@192.168.1.100  

 

3)查看A服务器是否把B服务的公钥传过去了

ll /root/.ssh/authorized_keys

 

4)测试B服务器免密码登录A服务器是否成功:

ssh root@192.168.1.100

 

5)在B服务器配置 sshfs 开机自动挂载

vim /etc/fstab

#在/etc/fstab 中添加挂载

sshfs#root@192.168.1.100:/home/data/ /home/sync_dir/ fuse defaults,auto,allow_other 0 0

 

解析:

root@192.168.1.100:/home/data/ #A服务器的用户@ip:需要同步的目录 B服务中挂载的目录 defaults,auto,allow_other 0 0

把ssh自动登录配置好,让root用户能够使用user身份登录远程主机,另外allow_other这个参数很重要,没有这个参数的话,挂载过来的目录只有root能够访问。

 

取消挂载的命令(先cd出这个挂载的目录):

fusermount -zu /home/sync_dir/

 

posted @ 2021-08-09 11:25  momomoi  阅读(119)  评论(0编辑  收藏  举报