#!/bin/bash
# Vmware workshop 时常出现网卡的mac地址和IP地址发生改变的情况,本脚本用于还原网卡配置文件中的真实MAC地址。
# 但请在还原配置文件前备份您的网卡配置文件(固定IP地址)
# By
[email protected]
# Sun May 10 20:07:51 CST 2009
# 2009-06-08 00:51:30
# 2009-08-30 13:02:08 Added: test ifcfg-eth*.bak exist
# 2009-09-07 21:41:15 tidy codes
# 2009-09-09 23:18:39 add comments
# 记录日志
exec 2>> $0.error
# 提供帮助信息
Usage(){
case $1 in
how)
echo "Usage: `basename $0` <eth0 IP> [ <eth1 IP> [ ... <ethn IP> ]]"
exit 1
;;
IPerror)
echo "Wrong host IP : $2"
exit 2
;;
IFerror)
echo "The interface eth$1 is not found! "
exit 3
;;
esac
}
# 测试IP地址是否合法,合法则返回IP的掩码,不合法返回错误信息
IPmask(){
# 把IP分段处理,存储到数组IP中
IP=(`echo $1 | awk 'BEGIN{RS=".";ORS=" "}{print $0}'`)
# 测试每段的值,来判断IP的掩码
# 非法的IP地址(包含D类地址),不做判断,返回错误信息
[ ${IP[1]} -gt 255 -o ${IP[2]} -gt 255 ] && Usage IPerror $1
[ ${IP[0]} -ge 224 -o ${IP[0]} -lt 0 -o ${IP[3]} -ge 255 -o ${IP[3]} -le 1 ] && Usage IPerror $1
# 分别判断是ABC哪一类地址
if [ ${IP[0]} -gt 191 ]; then
echo -n "255.255.255.0"
elif [ ${IP[0]} -gt 127 ]; then
echo -n "255.255.0.0"
else echo -n "255.0.0.0"
fi
}
# 没有参数时显示帮助信息。
if [ $# -lt 1 ]; then
Usage how
fi
cd /etc/sysconfig/network-scripts
# 测试所设置的网卡参数是否合法
for i in `seq 0 $(($#-1))`
do
if [ ! -f ifcfg-eth$i ]; then
Usage IFerror eth$i
fi
if eval IPmask \$$((i+1)) >/dev/null; then
continue
fi
done
# 自动生成配置模板
cat > ifconfig.mod <<-'End-of-ifconfig-mod'
# Advanced Micro Devices [AMD] 79c970 [PCnet32 LANCE]
DEVICE=eth2
BOOTPROTO=none
ONBOOT=yes
HWADDR=00:0C:29:0B:B5:DC
NETMASK=255.255.255.0
IPADDR=192.168.2.2
TYPE=Ethernet
End-of-ifconfig-mod
# 替换默认的网卡配置文件的备份
for i in `seq 0 $(($#-1))`
do
cp --verbose --interactive ifconfig.mod ifcfg-eth$i.bak
echo "Copying the template interface configure files : ifcfg-eth$i.bak ([No]|Yes)"
done
j=0
while [ $# -gt 0 -a -f ifcfg-eth$j.bak ]
do
# 修改备份好的模板文件
sed -ri 's/^(NETMASK=).*$/\1'$(IPmask $1)'/' ifcfg-eth$j.bak
sed -ri 's/^(IPADDR=).*$/\1'$1'/' ifcfg-eth$j.bak
sed -ri 's/^(DEVICE=eth).$/\1'$j'/' ifcfg-eth$j.bak
sed -ri "s/^(HWADDR=).*$/\1`ifconfig eth$j | head -1 | awk '{ print $NF }'`/" ifcfg-eth$j.bak
# 或者使用:sed -ri "s/^(HWADDR=).*$/\1`echo $(ifconfig eth0 | head -1 | awk '{ print $NF }')`/" ifcfg-eth0.bak
# 还原网卡eth0的配置文件,请确认
cp --verbose --interactive ifcfg-eth$j.bak ifcfg-eth$j
echo "Please confirm ([No]|Yes)"
((j++))
shift
done
rm -rf ifconfig.mod
# 重新启动网卡
/etc/rc.d/init.d/network restart
# 把dhclient进程杀死,因为虚拟机总是受默认dhcp网关的影响
if pkill dhclient; then
echo "The process of 'DHCP Client' has been killed just now!!!! "
else
echo "The process of 'DHCP Client is not exsit always! "
fi