大树

 

shell脚本自动修改linux下ifcfg-ethx文件

说明:此脚本作用

1)当发现网卡为dhcp模式时,修改为static模式,并添加IP等信息;

2)修改网卡IP为指定的IP

#!/bin/bash

FILE_PATH1=/etc/sysconfig/network-scripts/ifcfg-eth0
FILE_PATH2=/etc/sysconfig/network-scripts/ifcfg-eth1

#the last ipaddr netmask gateway for ifcfg-eth0
IP_MODI1=192.168.X.X

MASK_MODI1=255.255.255.0
GATEWAY_MODI1=""

#the last ipaddr netmask gateway for ifcfg-eth1
IP_MODI2=192.168.Y.Y

MASK_MODI2=255.255.255.0
GATEWAY_MODI2=""

change_dhcp()
{
 #edit eth0
 sed -i 's/dhcp/static/g' $FILE_PATH1 #change 'dhcp' to 'static'
 echo IPADDR=$IP_MODI1>> $FILE_PATH1
 echo NETMASK=$MASK_MODI1>> $FILE_PATH1
 echo GATEWAY=$GATEWAY_MODI1>> $FILE_PATH1
 #edit eth1
 sed -i 's/dhcp/static/g' $FILE_PATH2 #change 'dhcp' to 'static'
 echo IPADDR=$IP_MODI2>> $FILE_PATH2
 echo NETMASK=$MASK_MODI2>> $FILE_PATH2
 echo GATEWAY=$GATEWAY_MODI2>> $FILE_PATH2
}

change_static()
{
 #get primal ip from eth0
 IP_PRIMAL1=`grep -i ipaddr $FILE_PATH1|awk -F "=" '{printf $2 }'`
 #get primal netmask from eth0
 MASK_PRIMAL1=`grep -i netmask $FILE_PATH1|awk -F "=" '{printf $2}'`
 #get primal gateway from eth0
 GATEWAY_PRIMAL1=`grep -i gateway $FILE_PATH1|awk -F "=" '{printf $2}'`

 #get primal ip from eth1
 IP_PRIMAL2=`grep -i ipaddr $FILE_PATH2|awk -F "=" '{printf $2 }'`
 #get primal netmask from eth1
 MASK_PRIMAL2=`grep -i netmask $FILE_PATH2|awk -F "=" '{printf $2}'`
 #get primal gateway from eth1
 GATEWAY_PRIMAL2=`grep -i gateway $FILE_PATH2|awk -F "=" '{printf $2}'`

 #update ipaddr netmask and save ifcfg-eth0.bak file
# sed -e "s/$IP_PRIMAL1/$IP_MODI1/g" -e "s/$MASK_PRIMAL1/$MASK_MODI1/g" -e "s/$GATEWAY_PRIMAL1/$GATEWAY_MODI1/g" $FILE_PATH1>ifcfg-eth0.bak
 sed -i -e "s/$IP_PRIMAL1/$IP_MODI1/g" $FILE_PATH1
 sed -i -e "s/$MASK_PRIMAL1/$MASK_MODI1/g" $FILE_PATH1
 sed -i -e "s/$GATEWAY_PRIMAL1/$GATEWAY_MODI1/g" $FILE_PATH1
 
 sed -i -e "s/$IP_PRIMAL2/$IP_MODI2/g" $FILE_PATH2
 sed -i -e "s/$MASK_PRIMAL2/$MASK_MODI2/g" $FILE_PATH2
 sed -i -e "s/$GATEWAY_PRIMAL2/$GATEWAY_MODI2/g" $FILE_PATH2

 
 #update ipaddr netmaskand save ifcfg-eth1.bak file
# sed -e "s/$IP_PRIMAL2/$IP_MODI2/g" -e "s/$MASK_PRIMAL2/$MASK_MODI2/g" -e "s/$GATEWAY_PRIMAL2/$GATEWAY_MODI2/g" $FILE_PATH2>ifcfg-eth1.bak

 #update ifcfg-eth0 and ifcfg-eth1 file
# \cp ifcfg-eth0.bak $FILE_PATH1
# \cp ifcfg-eth1.bak $FILE_PATH2
}

change_run()
{
 service network restart
 #show network card information
 cat $FILE_PATH1
 cat $FILE_PATH2
}

#get bootproto
boot_model1=`grep -i bootproto $FILE_PATH1|awk -F "=" '{printf $2 }'`
boot_model2=`grep -i bootproto $FILE_PATH2|awk -F "=" '{printf $2 }'`

if [[ $boot_model1 = "dhcp" ]] && [[ $boot_model2 = "dhcp" ]];then
 change_dhcp
 change_run
elif [[ $boot_model1 = "static" ]] && [[ $boot_model2 = "static" ]];then
 change_static
 change_run
else
 echo "please check the bootproto!"
fi

下载地址:http://d.download.csdn.net/down/3316112/drew27

posted on 2011-05-26 21:54  ruberzhu  阅读(2796)  评论(0编辑  收藏  举报

导航