使用前提

  • 服务器间配置了ssh 免密登录
  • /etc/hosts 文件配置了主机名

详情见:SSH 免密登录

xcall(同步执行命令脚本)

说明

  • 在一个节点上输入命令可以同步到其余节点执行
  • 建议创建脚本目录为:/usr/local/bin

操作

1
vim /usr/local/bin/xcall

内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#!/bin/bash

# 获取控制台指令

cmd=$*

# 判断指令是否为空
if [ ! -n "$cmd" ]
then
echo "command can not be null !"
exit
fi

# 获取当前登录用户
user=`whoami`

# 在主机执行指令
$cmd

# 在从机执行指令
# 注意:下面 ssh $user@node$host $cmd 中的 @node 需要改为自己的主机名
# 比如我的从机名是 SG1 ,则对应的是 ssh $user@SG$host $cmd

for (( host=1;host<=1;host++ ))
do
echo "================current host is SG$host================="
echo "--> excute command \"$cmd\""
ssh $user@node$host $cmd
done

echo "excute successfully !"

赋予权限

1
chmod 777 /usr/local/bin/xcall

尝试执行

1
xcall ls

效果

xsync(同步文件目录)

说明

  • 将文件或目录同步到集群的其他节点
  • 在使用之前,所有节点均需要安装 rsync 服务(yum install rsync -y,这里就可以用上面配置的 xcall yum install rsync -y 来完成安装)
  • 建议创建脚本目录为:/usr/local/bin

操作

1
vim /usr/local/bin/xsync

内容如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#!/bin/bash

# 获取输出参数,如果没有参数则直接返回
pcount=$#
if [ $pcount -eq 0 ]
then
echo "no parameter find !";
exit;
fi

# 获取传输文件名
p1=$1
filename=`basename $p1`
echo "load file $p1 success !"

# 获取文件的绝对路径
pdir=`cd -P $(dirname $p1); pwd`
echo "file path is $pdir"

# 获取当前用户(如果想使用root用户权限拷贝文件,在命令后加入-root参数即可)
user=$2
case "$user" in
"-root")
user="root";;
"")
user=`whoami`;;
*)
echo "illegal parameter $user"

esac

echo $user

# 拷贝文件到从机
# 注意:下面 rsync -rvl $pdir/$filename $user@node$host:$pdir 中的 @node 需要改为自己的主机名
# 比如我的从机名是 SG1 ,则对应的是 rsync -rvl $pdir/$filename $user@SG$host:$pdir

for (( host=1;host<=1;host++ ))
do
echo "================current host is SG$host================="
rsync -rvl $pdir/$filename $user@node$host:$pdir
done

echo "complate !"

赋予权限

1
chmod 777 /usr/local/bin/xsync

测试

1
2
touch 1.txt
vim 1.txt

里面输入个 hello world

同步文件

1
xsync 1.txt