跳转至

CentOS 配置多IP脚本


2015-02-09 by dongnan

环境

# 操作系统
head -n1 /etc/issue
CentOS release 6.6 (Final)

# 内核版本
uname -r
2.6.32-504.3.3.el6.x86_64

目标

使用shell脚本快速配置多个IP地址。

脚本

核心是 ifconfig命令,例如 ifconfig eth0:52 173.22.52. netmask 255.255.255.240 up

#!/bin/bash
#20141225 by dongnan

#variables
my_net1="173.2x.3x."
my_mask1="255.255.255.248"
my_net2="173.2x.1x."
my_mask2="255.255.255.240"

#functions
mip_up (){

#my_net1
for((i=52;i<=53;i++));do
    if ifconfig eth0:"$i" | grep "inet addr:" > /dev/null 2>&1;then
        echo "${my_net1}$i is already exists !"
        continue;
    else
        ifconfig eth0:$i "${my_net1}$i" netmask "$my_mask1" up && echo "${my_net1}$i is up"
        test -e /bin/usleep && usleep 200 || sleep 1
    fi
done

#my_net2
for((i=242;i<=254;i++));do
    if ifconfig eth0:"$i" | grep "inet addr:" > /dev/null 2>&1;then
        echo "${my_net2}$i is already exists !"
        continue;
    else
        ifconfig eth0:$i "${my_net2}$i" netmask "$my_mask2" up && echo "${my_net2}$i is up"
        test -e /bin/usleep && usleep 200 || sleep 1
    fi
done

}

mip_down (){

#my_net1
for((i=52;i<=53;i++));do
    if ! ifconfig eth0:"$i" | grep "inet addr:" > /dev/null 2>&1;then
        echo "${my_net1}$i does not exist!"
        continue;
    else
        ifconfig eth0:$i "${my_net1}$i" netmask "$my_mask1" down && echo "${my_net1}$i is down"
        test -e /bin/usleep && usleep 200 || sleep 1
    fi
done

#my_net2
for((i=242;i<=254;i++));do
    if ! ifconfig eth0:"$i" | grep "inet addr:" > /dev/null 2>&1;then
        echo "${my_net2}$i does not exist!"
        continue;
    else
        ifconfig eth0:$i "${my_net1}$i" netmask "$my_mask2" down && echo "${my_net2}$i is down"
        test -e /bin/usleep && usleep 200 || sleep 1
    fi
done

}


#main
case "$1" in
    start)
        mip_up
        ;;
    stop)
        mip_down
        ;;
    *)
        echo $"Usage: $0 {start|stop}"
        ;;
esac

使用

# 需要root权限
mip.sh start



回到页面顶部