您的当前位置:首页正文

集群内快速同步配置

2024-11-08 来源:个人技术集锦

本文转至 文章 ,欢迎访问 了解更多信息!

场景再现

在多数集群中,节点的配置必须保持一致,一旦管理节点修改了配置,就需要把配置同步到其他节点,通常情况下是下面这样的,它的缺点是每次都需要写全路径。

scp -r /path/conf node1:/path/conf
scp -r /path/conf node2:/path/conf
scp -r /path/conf node3:/path/conf

解决方法

使用 rsync 命令同步,同时自动获取到文件的绝对路径,脚本如下

  • 同步配置文件 sudo vim /usr/bin/xsync
    sudo chmod +x /usr/bin/xsync
#!/bin/bash
[ $# -lt 1 ] && { echo Not Enough Arguement!; exit 1; }

# nodes must can login without password
nodes=(node1 node2 node3)

echo -n "Action Executing ON HOSTS: ${nodes[@]}, [yes/no] "
read input
[ "$input" == "yes" ] || exit 1
for host in "${nodes[@]}"
do
    echo ==================== sync to $host  ====================
    for file in $@
    do
        if [ -e $file ]; then
            pdir=$(cd -P $(dirname $file); pwd)
            fname=$(basename $file)
            ssh $host "mkdir -p $pdir"
            rsync -apz $pdir/$fname $host:$pdir
        else
            echo $file does not exists!
        fi
    done
done

  • 远程删除 sudo vim /usr/bin/xremove
    sudo chmod +x /usr/bin/xremove
#!/bin/bash
[ $# -lt 1 ] && { echo Not Enough Arguement!; exit 1; }

# nodes must can login without password
nodes=(node1 node2 node3)

echo -n "Action Executing ON HOSTS: ${nodes[@]}, [yes/no] "
read input
[ "$input" == "yes" ] || exit 1
for host in "${nodes[@]}"
do
    echo ==================== removing on $host  ====================
    for file in $@
    do
        pdir=$(cd -P $(dirname $file); pwd)
        fname=$(basename $file)
        fpath="$pdir/$fname"
        ssh $host "[ -e $fpath ] && rm -rf $fpath || echo $file does not exists!"
    done
done

  • 远程执行命令 sudo vim /usr/bin/xcmd
    sudo chmod +x /usr/bin/xcmd
#!/bin/bash
[ $# -lt 1 ] && { echo Not Enough Arguement!; exit 1; }

# nodes must can login without password
nodes=(node1 node2 node3)

echo -n "Action Executing ON HOSTS: ${nodes[@]}, [yes/no] "
read input
[ "$input" == "yes" ] || exit 1
for host in "${nodes[@]}"
do
    echo ==================== removing on $host  ====================
    for file in $@
    do
        cdir="$(pwd)"
        ssh $host "cd $cdir; $@"
    done
done

使用示例

# 同步 /etc/profile
sudo xsync /etc/profile

# 同步当前目录的tmpfile
xsync tmpfile

# 删除所有的 /tmp/tmpfile
xremove /tmp/tmpfile


本文转至 文章 ,欢迎访问 了解更多信息!

显示全文