2013/03/27

CentOS/windows自動切換DHCP與固定IP



由於目前工作所需

常常會需要切換DHCP與固定IP

以下提供一個script


CentOS:
#! /bin/sh -e

type=$1
ETH=eth0
MAC=$(ifconfig $ETH | grep "HWaddr" | sed 's/^.*HWaddr //')


NET_SCRIPT_PATH=/etc/sysconfig/network-scripts
#/etc/init.d/network stop
echo 正在關閉 $ETH 
$NET_SCRIPT_PATH/ifdown $ETH

# DHCP
if [ "$type" ==  "dhcp" -o "$type" == "d" ]; then
        echo DHCP_HOSTNAME=$(hostname) > $NET_SCRIPT_PATH/ifcfg-$ETH
        echo DEVICE=$ETH >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo BOOTPROTO=dhcp >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo ONBOOT=yes >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo HWADDR=$MAC >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo TYPE=Ethernet >> $NET_SCRIPT_PATH/ifcfg-$ETH
# 192.168.10.200
elif [ "$type" == "10" ]; then
        echo DEVICE=$ETH > $NET_SCRIPT_PATH/ifcfg-$ETH
        echo BOOTPROTO=none >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo ONBOOT=yes >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo HWADDR=$MAC >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo TYPE=Ethernet >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo NETMASK=255.255.255.0 >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo IPADDR=192.168.10.200 >> $NET_SCRIPT_PATH/ifcfg-$ETH
        #192.168.10.200改為你要的固定IP
        echo USERCTL=no >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo IPV6INIT=no >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo PEERDNS=yes >> $NET_SCRIPT_PATH/ifcfg-$ETH
# 以下為第二組設定
# 192.168.0.200
elif [ "$type" == "0" ]; then
        echo DEVICE=$ETH > $NET_SCRIPT_PATH/ifcfg-$ETH
        echo BOOTPROTO=none >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo ONBOOT=yes >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo HWADDR=$MAC >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo TYPE=Ethernet >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo NETMASK=255.255.255.0 >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo IPADDR=192.168.0.200 >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo USERCTL=no >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo IPV6INIT=no >> $NET_SCRIPT_PATH/ifcfg-$ETH
        echo PEERDNS=yes >> $NET_SCRIPT_PATH/ifcfg-$ETH
fi

#/etc/init.d/network start
echo 正在啟動 $ETH 
$NET_SCRIPT_PATH/ifup $ETH > /dev/null
IP=$(ifconfig $ETH | grep "inet addr:" | sed 's/^.*inet addr://' | sed 's/Bcast.*$//')
echo 現在IP位置為: $IP

Windows:
(注意:命令提示自原需啟動為系統管理員模式)
@echo off


set ifname=乙太網路
rem set /p KEY=[KEY]
rem if %KEY% == d goto DHCP
rem if %KEY% == 0 goto ZERO
rem if %KEY% == 10 goto TEN

if %1 == d goto DHCP
if %1 == 0 goto ZERO
if %1 == 10 goto TEN

:ZERO
netsh interface ip set address name="%ifname%" source=static addr=192.168.0.2 mask=255.255.255.0 gwmetric=1
echo "ipaddr is 192.168.0.2"
goto END

:TEN
netsh interface ip set address name="%ifname%" source=static addr=192.168.10.2 mask=255.255.255.0 gwmetric=1
echo "ipaddr is 192.168.10.2"
goto END

:DHCP
netsh interface ip set address name="%ifname%" source=dhcp
echo "ipaddr is dhcp"
goto END

:END
rem pause


有以上腳本後只要執行

chnet d //DHCP
chnet 0 //192.168.0.x
chent 10 //192.158.10.x

就可以自己切換想要的IP了

沒有留言:

張貼留言