shell 编程实战修改IP及主机名

批量自动化安装LINUX系统后,IP均是自动获取的,而服务器要求固定的静态IP,百台服务器手工去配置静态IP是不可取的,可以基于shell脚本自动修改IP、主机名等信息。
shell脚本实现服务器IP、主机名自动修改及配置:
静态IP修改;
动态IP修改;
根据IP生成主机名并配置;
修改DNS域名解析。
shell脚本实现服务器IP、主机名自动修改及配置:
#!/bin/bash
#Auto Change ip netmaskgateway scripts
#By author tang.com2018
#Define Path variables
ETHCONF=/etc/sysconfig/network-scripts/ifcfg-ens33
HOSTS=/etc/hosts
NETWORK=/etc/sysconfig/network
DIR=/data/backup/`date+%Y%m%d`
NETMASK=255.255.255.0
echo"----------------------------------------------------------------------"
input_ip(){
read-p "Please enter ip Address,example 192.168.0.11 ip": IPADDR
echo$IPADDR |grep -v "[Aa-Zz]"|grep --color -E"([0-9]{1,3}\.){3}[0-9]{1,3}"
}
count_ip(){
count=(`echo$IPADDR |awk -F. '{print $1,$2,$3,$4}'`)
IP1=${count[0]}
IP2=${count[1]}
IP3=${count[2]}
IP4=${count[3]}
}
ip_check(){
input_ip
while [ $? -ne 0 ]
do
input_ip
done
count_ip
while ["$IP1" -lt 0 -o "$IP1" -ge 255 -o "$IP2" -ge 255-o "$IP3" -ge 255 -o "$IP4" -ge 255 ]
do
input_ip
while[ $? -ne 0 ]
do
input_ip
done
count_ip
done
}
change_ip(){
if [ ! -d $DIR ];then
mkdir-p $DIR
fi
echo "The Changeip address to Backup Interface ens33"
cp $ETHCONF $DIR
grep "dhcp"$ETHCONF
if [ $? -eq 0 ];then
read-p "Please enter ip Address :" IPADDR
sed-i 's/dhcp/static/g' $ETHCONF
echo-e "IPADDR=$IPADDR\nNETMASK=$NETMASK\nGATEWAY=`echo $IPADDR|awk -F.'{print $1"."$2"."$3}'`.2">>$ETHCONF
echo"The IP configuration success.!"
else
echo-n "Static IP has been configured,please confirm whether to modify,yes orno": read i
fi
if [ "$i" =="y" -o "$i" == "yes" ];then
ip_check
sed-i -e '/IPADDR/d' -e '/NETMASK/d' -e '/GATEWAY/d' $NETCONF
echo-e "IPADDR=$IPADDR\nNETMASK=$NETMASK\nGATEWAY=`echo $IPADDR|awk -F.'{print $1"."$2"."$3}'`.1">>$ETHCONF
echo"The IP configuration success.!"
echo
else
echo"Static IP already exists,please exit."
exit$?
fi
}
change_hosts(){
if [ ! -d $DIR ];then
mkdir-p $DIR
fi
cp $HOSTS $DIR
ip_check
host=`echo $IPADDR |sed's/\./-/g' |awk '{print "HZ-IDC-"$0"-tang.com"}'`
cat $HOSTS |grep"$host"
if [ $? -ne 0 ];then
echo"$IPADDR     $host" >>$HOSTS
echo"The hosts modify success"
fi
grep "$host"$NETWORK
if [ $? -ne 0 ];then
sed-i "s/^HOSTNAME/#HOSTNAME/g" $NETWORK
echo"NETWORK=$host" >> $NETWORK
hostname$host;su
fi
}
PS3="Please Selectconfiguration ip or configuration host :"
select i in"modify_ip" "modify_hosts" "exit"
do
case$i in
modify_ip)
change_ip
;;
modify_hosts)
change_hosts
;;
exit)
exit
;;
*)
echo-e "1)modify_ip\n2)modify_hosts\n3)exit"
esac
done