目录结构:
[root@localhost cluster]# pwd
/root/shell/cluster
[root@localhost cluster]# tree
.
├── config
├── hostname
│ └── sethname.sh
├── ssh
│ ├── CreateKey.sh
│ ├── DistributeFile.sh
│ └── TranPubKey.sh
└── sync
├── CmdSync.sh
├── FileSync.sh
└── readme.txt
config:
[root@localhost cluster]# cat config
[nodes]
200.201.200.85,200.201.200.89
[password]
adminsangfornetwork
[hostname]
node1,node2,node3
sethname.sh:
[root@localhost cluster]# cat hostname/sethname.sh
#!/bin/bash
#根据config中的配置设置主机名和同步hosts文件
CONF=../config
PraserConf(){
num=`sed -n -e '/^\['$1'\]/=' $CONF`
let temp=num+1
sed -n ''$temp'p' $CONF
}
nodes_str=`PraserConf nodes`
old_ifs="$IFS"
IFS=","
nodes=($nodes_str)
hostnames_str=`PraserConf hostname`
hostnames=($hostnames_str)
IFS=$old_ifs
if [ ! -f /etc/hosts.bak ]
then
cp /etc/hosts /etc/hosts.bak
else
cp -f /etc/hosts.bak /etc/hosts
fi
if [ ${#nodes[*]} -eq ${#hostnames[*]} ]
then
for i in `seq ${#nodes[*]}`
do
let temp=i-1
echo -e "\e[34m******${nodes[$temp]}******\e[0m"
ssh root@${nodes[$temp]} "echo ${hostnames[$temp]}>/etc/hostname"
ssh root@${nodes[$temp]} "hostname ${hostnames[$temp]}"
echo ${nodes[$temp]} ${hostnames[$temp]}>>/etc/hosts
done
else
echo -e "\e[34m******please check config file******\e[0m"
fi
for node in ${nodes[*]}
do
scp /etc/hosts root@$node:/etc/hosts >/dev/null 2>&1
done
CreateKey.sh:
[root@localhost ssh]# cat CreateKey.sh
#!/bin/bash
#create ssh key
CreateKey(){
if [ ! -f /root/.ssh/id_rsa ]
then
ssh-keygen -t rsa -f /root/.ssh/id_rsa -P '' >/dev/null
fi
}
CreateKey
DistributeFile.sh:
[root@localhost ssh]# cat DistributeFile.sh
#!/bin/bash
#解析配置文件
#解析配置文件获取节点ip和密码
CONF=../config
PraserConf(){
num=`sed -n -e '/^\['$1'\]/=' $CONF`
temp=`expr $num + 1`
sed -n ''$temp'p' $CONF
}
nodes_str=`PraserConf nodes`
old_ifs="$IFS"
IFS=","
nodes=($nodes_str)
#echo ${nodes[*]}
pd=`PraserConf password`
DistributeFile(){
for node in ${nodes[*]}
do
sshpass -p $1 scp -r -o "StrictHostKeyChecking no" ../../cluster root@$node:/root >/dev/null 2>&1
sshpass -p $1 ssh -o "StrictHostKeyChecking no" root@$node "bash /root/cluster/ssh/CreateKey.sh" >/dev/null
done
for node in ${nodes[*]}
do
sshpass -p $1 ssh -o "StrictHostKeyChecking no" root@$node "bash /root/cluster/ssh/TranPubKey.sh"
#sshpass -p $1 ssh -o "StrictHostKeyChecking no" root@$node "rm -rf /root/cluster"
done
}
DistributeFile $pd
TranPubKey.sh:
#!/bin/bash
#解析配置文件获取节点ip和密码
CONF=/root/cluster/config
PraserConf(){
num=`sed -n -e '/^\['$1'\]/=' $CONF`
temp=`expr $num + 1`
sed -n ''$temp'p' $CONF
}
nodes_str=`PraserConf nodes`
old_ifs="$IFS"
IFS=","
nodes=($nodes_str)
#echo ${nodes[*]}
pd=`PraserConf password`
TranPubKey(){
if [ -f /root/.ssh/id_rsa.pub ]
then
for node in ${nodes[*]}
do
sshpass -p $1 ssh-copy-id -i /root/.ssh/id_rsa.pub root@$node >/dev/null 2>&1
#sshpass -p $1 ssh-copy-id -o "StrictHostKeyChecking no" -i /root/.ssh/id_rsa.pub root@$node >/dev/null 2>&1
done
fi
}
TranPubKey $pd