linux shell脚本配置IP的实现代码

发布时间:2019-09-19编辑:脚本学堂
分享一例shell脚本,实现linux ip地址的程序化配置,包括dhcp自动获取ip地址与手动配置ip地址二种情况,需要的朋友参考下。

linux shell/ target=_blank class=infotextkey>shell脚本
 

复制代码 代码示例:

#!/bin/bash
# 配置IP地址脚本

fun0 () {
        ipfile="/etc/sysconfig/network-scripts/ifcfg-eth0"
        hwaddr=`ifconfig |grep eth0 |awk -F " " '{print $5}'`
        device=`ifconfig |grep eth0 |awk -F " " '{print $1}'`
        type=`ifconfig |grep eth0 |awk -F ":" '{ print $2 }'|awk -F " " '{
print $1 }'`
        echo "DEVICE=$device" > $ipfile
        echo "HWADDR=$hwaddr" >>$ipfile
        echo "ONBOOT=yes" >>$ipfile
        echo "TYPE=$type" >>$ipfile
}
fun1 () {
         echo "Enter the IP that you want to set:"
        read IP
        echo "Enter the netmask:"
        read netmask
        echo "Enter the gateway:"
        read gateway
        echo "Enter the DNS:"
        read dns
}
echo "Enter the IP model you want to set (DHCP/STATIC):"
read model
if [ $model = "DHCP" ]
then
        fun0
        echo "BOOTPROTO=dhcp" >>$ipfile
        service network restart
elif [ $model = "STATIC" ]
then
        fun1
        fun0
        echo "BOOTPROTO=none" >>$ipfile
        echo "NETMASK=$netmask" >>$ipfile
        echo "IPADDR=$IP" >>$ipfile
        echo "GATEWAY=$gateway" >>$ipfile
        echo "$dns" > /etc/resolv.conf
        service network restart

else
        echo "error:please enter DHCP or STATIC"
        exit 0
fi