shell修改ip、网关、DNS

以centos7.6为例

#!/bin/bash
#__author__ : lalone

# @l_ip:ip
# @l_network:掩码
# @l_gateway:网关
# @l_dns_1:DNS
# @l_dns_2:DNS
l_ip="10.10.50.4"
l_network="255.255.0.0"
l_gateway="10.10.200.1"
l_dns_1="114.114.114.114"
#l_dns_2="8.8.8.8"
l_dns_2=""

if [ $# -eq 4 ];
then
        l_ip=$1
        l_network=$2
        l_gateway=$3
        l_dns_1=$4
elif [ $# -eq 5 ];
then
        l_ip=$1
        l_network=$2
        l_gateway=$3
        l_dns_1=$4
        l_dns_2=$5
else
        echo "输入参数有误,请重新输入。"
        echo "./ip.sh ip 掩码 网关 DNS1 [DNS2可选]"
        echo "eg: ./ip.sh 10.10.50.4 255.225.0.0 10.10.200.1 114.114.114.114 [8.8.8.8]"
fi

# 修改IP地址
# /etc/sysconfig/network-scripts/ifcfg-eth0
function changeIP(){
        file="/etc/sysconfig/network-scripts/ifcfg-eth0"
        # 设置为静态
        if grep -q "BOOTPROTO" $file;
        then
                sed -i s/^BOOTPROTO.*/BOOTPROTO=\'static\'/ $file
        else
                echo "BOOTPROTO=static" >> $file
        fi
        # 设置IP
        if grep -q "IPADDR" $file;
        then
                sed -i s/^IPADDR.*/IPADDR=${1}/ $file
        else
                echo "IPADDR=${1}" >> $file
        fi
        # 设置掩码
        if grep -q "NETMASK" $file;
        then
                sed -i s/^NETMASK.*/NETMASK=${2}/ $file
        else
                echo "NETMASK=${2}" >> $file
        fi
        echo "IP更改成功。"
}

if [ ! -z "$l_ip" ] && [ ! -z "$l_network" ];
then
        changeIP $l_ip $l_network
else
        echo "IP或掩码配置为空,未更改。"
fi

# 修改默认网关
# /etc/sysconfig/network
function changeNetwork(){
        file="/etc/sysconfig/network"
        if grep -q "GATEWAY" $file;
        then
                sed -i s/^GATEWAY.*/GATEWAY=${1}/ $file
        else
                echo "GATEWAY=${1}" >> $file
        fi
        echo "网关更改成功"
}

if [ ! -z "$l_gateway" ];
then
        changeNetwork $l_gateway
else
        echo "网关配置为空,未更改。"
fi

# 修改DNS
# /etc/resolv.conf
function changeDNS(){
        file="/etc/resolv.conf"
        echo "# Generated by NetworkManager" > $file
        #echo `cat $file`
        if [ $# -eq 2 ];
        then
                echo "nameserver ${1}" >> $file
                echo "nameserver ${2}" >> $file
                echo "DNS更改成功"
        elif [ $# -eq 1 ];
        then
                echo "nameserver ${1}" >> $file
                echo "DNS更改成功"
        else
                echo "DNS更改失败"
        fi
        #echo `cat $file`
}

if [ ! -z "$l_dns_1" ] && [ ! -z "$l_dns_2" ];
then
        changeDNS $l_dns_1 $l_dns_2
elif [ ! -z "$l_dns_1" ] && [ -z "$l_dns_2" ];
then
        changeDNS $l_dns_1
elif [ -z "$l_dns_1" ] && [ ! -z "$l_dns_2" ];
then
        changeDNS $l_dns_2
else
        echo "DNS配置为空,未更改。"
fi

/etc/init.d/network restart

注意:实际应用过程中根据自己系统类型版本,修改相应的file指定文件名。

你可能感兴趣的:(linux)