变更CentOS6模板机
需要收集模板机克隆之后可能的vlan信息,并写入配置文件:
cat >/root/checkOS/cloneOS.lst<<EOF
# IP NETMASK GATEWAY
192.168.77.10 255.255.255.0 192.168.77.1
192.168.1.10 255.255.255.0 192.168.1.1
EOF
# 模板机克隆后在各个vlan中占用的IP以及相对应的子网掩码和网关地址
简单的自适应脚本:
cat >/root/checkOS/cloneOS.sh<<EOF
#!/bin/bash
source ~/.bash_profile
# udev中的最后一个网卡信息和网卡名
EtherInfo=\$(tail -1 /etc/udev/rules.d/70-persistent-net.rules)
EtherName=\$(echo \${EtherInfo} |awk -F'"' '{print \$(NF-1)}')
# 配置文件中的默认网关
DefaultGW=\$(grep 'GATEWAY' /etc/sysconfig/network-scripts/ifcfg-eth0 |awk -F'=' '{print \$2}')
# 测试当前网络是否正常
ping -c 3 \${DefaultGW} &>/dev/null
NetStat=\$?
# 如果网卡不是eth0,则修改并重启
if [ \${EtherName} != 'eth0' ]
then
echo "[+] \$(date +%F_%T) 1 modify udev">>/root/checkOS/cloneOS.log
EtherInfo=\$(tail -1 /etc/udev/rules.d/70-persistent-net.rules)
echo "\${EtherInfo}"|sed "s/\${EtherName}/eth0/g">/etc/udev/rules.d/70-persistent-net.rules
reboot
exit 0
fi
# 如果网络正常,则取消脚本自动运行
if [ \${NetStat} -eq 0 ]
then
echo "[+] \$(date +%F_%T) 2 remove auto exec">>/root/checkOS/cloneOS.log
sed -i '/^.*cloneOS.sh\$/d' /etc/rc.d/rc.local
mv /root/checkOS/cloneOS.* /tmp
exit 0
else
# 根据配置的可用的vlan信息,测试并修改网络配置
grep -Ev '^#|^$' /root/checkOS/cloneOS.lst |while read line
do
Ip=\$(echo \${line}|awk '{print \$1}')
Netmask=\$(echo \${line}|awk '{print \$2}')
Gateway=\$(echo \${line}|awk '{print \$3}')
echo "[+] \$(date +%F_%T) 3 test \${Ip} \${Netmask} \${Gateway}">>/root/checkOS/cloneOS.log
ifconfig eth0 \${Ip} netmask \${Netmask}
route add default gw \${Gateway}
ping -c 3 \${Gateway} &>/dev/null
NetStat=\$?
echo "[+] \$(date +%F_%T) 4 test result \${NetStat}">>/root/checkOS/cloneOS.log
if [ \${NetStat} -eq 0 ]
then
echo "[+] \$(date +%F_%T) 5 modify \${Ip} \${Netmask} \${Gateway}">>/root/checkOS/cloneOS.log
sed -i "s/\(IPADDR=\).*/\1\${Ip}/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/\(GATEWAY=\).*/\1\${Gateway}/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/\(NETMASK=\).*/\1\${Netmask}/g" /etc/sysconfig/network-scripts/ifcfg-eth0
# 如果网络正常,则取消脚本自动运行
echo "[+] \$(date +%F_%T) 6 remove auto exec">>/root/checkOS/cloneOS.log
sed -i '/^.*cloneOS.sh\$/d' /etc/rc.d/rc.local
mv /root/checkOS/cloneOS.* /tmp
# 建议重启,有一些依赖于正常网络的配置,如开机的ntpdate时间矫正需要重跑
reboot
exit 0
fi
done
fi
EOF
echo '/root/checkOS/cloneOS.sh' >>/etc/rc.d/rc.local
chmod +x /root/checkOS/cloneOS.sh
脚本存在的缺陷:
当vlan信息变更时,如新增一个vlan,需要维护模板机的cloneOS.lst
如果在一台已经配置好IP的机器上修改vlan,再次执行该功能,需要手动重新部署
[TOC]