在生产环境线上,服务器统一命名是非常重要的,它遵循了环境标准化,使运维工程师能够更方便的管理线上服务器,当出现问题时,能够快速的定位问题、排查问题、解决问题。
编写脚本思路:
1、基于ssh-key生产秘钥
2、基于ssh与其他节点完成第一次交互(yes/no)
3、基于ssh-copy-id实现远程批量推送秘钥
4、基于sed来修改不同集群的不同主机名
测试环境:
| 主机名 | IP |
| [root@node1 ~]# | 10.10.73.148 |
| [root@node2 ~]# | 10.10.73.149 |
| [root@node3 ~]# | 10.10.73.192 |
一、以10.10.73.148(node1)节点为生成秘钥节点,推送给node2、node3,并修改主机名!
[root@node1 ~]# vim /tmp/lweim.sh
#!/bin/bash
#Version:1.0
#Author:wtc
#Use:Change Hostname
ip="148 149 192"
key=umpay.com
main() {
if ! ‘rpm -q expect‘ &> /dev/null;then
yum install expect -y &> /dev/null
[[ $? -eq 0 ]] && echo "Install Success" || echo "Install Faile"
[ -a /root/.ssh/id_rsa ] && rm -rf /root/.ssh/*
Create_Key
for n in $ip;do
for i in 10.10.73.$n;do
First_HandShake
Push_Key
done
done
else
exit 1
fi
}
Create_Key() {
echo "Creating RSA Key ...."
`which expect` <<END &> /dev/null
set timeout 60
spawn ssh-keygen
expect "save"
send "\r"
expect "passparase"
send "\r"
expect "again"
send "\r"
expect eof
END
[[ $? -eq 0 ]] && echo "Creating RSA Success" || echo "Create RSA Key Faile"
}
First_HandShake() {
echo "First HandShake with $ip"
`which expect` <<END &> /dev/null
set timeout 5
spawn ssh $i
expect "(yes/no)"
send "yes\r"
expect eof
END
[[ $? -eq 0 ]] && echo "First HandShake with $i Success" || echo "First HandShake with $i Faile"
}
Push_Key() {
echo "Push RSA Key to $i"
`which expect` <<END &> /dev/null
set timeout 60
spawn ssh-copy-id $i
expect "password"
send "$key\r"
expect eof
END
[[ $? -eq 0 ]] && echo "Push Key to $i Success" || echo "Push Key to $i Faile"
}
main
##############[ 修改"node1"、"node2"主机名为"mysql_01"、"mysql_02" ]##############
ip="148 149"
declare -x x=1
for n in $ip;do
for i in 10.10.73.$n;do
ssh $i "sed -i s/^HOST.*/HOSTNAME=mysql_0$x/ /etc/sysconfig/network"
let x++
done
done
##############[ 修改"node3"的主机名为"umpay_01"] ##############
ip="192"
declare -x x=1
for n in $ip;do
for i in 10.10.73.$n;do
ssh $i "sed -i s/^HOSTNAME.*/HOSTNAME=umpay_0$x/ /etc/sysconfig/network"
let x++
done
done
测试结果:
[root@node1 tmp]# bash -x lweim.sh
| 主机名 | IP |
| [root@mysql_01 ~]# | 10.10.73.148 |
| [root@mysql_02 ~]# | 10.10.73.149 |
| [root@umpay_01 ~]# | 10.10.73.192 |
本文出自 “wtc” 博客,请务必保留此出处http://wangtianci.blog.51cto.com/11265133/1843201
原文地址:http://wangtianci.blog.51cto.com/11265133/1843201