尚硅谷-xsync集群分发脚本

发布时间 2024-01-02 13:35:28作者: SpringCore

1.安装 rsync远程同步工具

apt install -y rsync

2.配置host映射【略】

vi /etc/hosts

3.配置SSH免密登录

使用SSH远程登陆Linux

4.编写xsync集群分发脚本

vi /usr/bin/xsync
#! /bin/bash
#1 获取输入参数个数,如果没有参数,直接退出
pcount=$#
if [ $pcount -lt 1 ]
then
    echo No Enough Arguement!
    exit;
fi

#2. 遍历集群所有机器
for host in 192.168.58.130 192.168.58.131 192.168.58.132
do
    echo ====================    $host    ====================
    #3. 递归遍历所有目录
    for file in $@
    do
        #4 判断文件是否存在
        if [ -e $file ]
        then
            #5. 获取全路径
            pdir=$(cd -P $(dirname $file); pwd)
            echo pdir=$pdir
            
            #6. 获取当前文件的名称
            fname=$(basename $file)
            echo fname=$fname
            
            #7. 通过ssh执行命令:在$host主机上递归创建文件夹(如果存在该文件夹)
            ssh $host "source /etc/profile;mkdir -p $pdir"
            
            #8. 远程同步文件至$host主机的$USER用户的$pdir文件夹下
            rsync -av $pdir/$fname $USER@$host:$pdir
        else
            echo $file Does Not Exists!
        fi
    done
done

5.赋予执行脚本执行权限

chmod +x /usr/bin/xsync

6.测试

xsync filename/dirname