学习笔记之ubuntu修改固定IP脚本

一、shell脚本编程

二、正则表达式

三、linux修改IP的方法

#!/bin/bash

cd /etc/network/

stty erase '^?'

write_interfaces()
{
echo "auto lo
iface lo inet loopback

auto eth0
iface eth0 inet static
address $1
netmask 255.255.255.0
gateway $2
" > interfaces
}

reboot_fun()
{
        echo "reboot now?(Y/N)"
        read reb_in 

        if [[ ${reb_in} = $'Y' || ${reb_in} = $'y' ]]
        then
                echo "reboot now"
                reboot
        else
                echo "pls reboot if you can not ping the IP"
        fi      
}

ping_func()
{
        ping -c 3  $set_IP && result=1 || result=0
        if [ $result -eq 1 ]
        then
        {
                echo "set Ip conflict"
                continue
                IP_INPUT=0
        }
        fi

        if [ $result -eq 0 ]
        then
        {
                echo "IP is ok:$set_IP"

                write_interfaces $set_IP $GateWay
                /etc/init.d/networking reload
                /etc/init.d/networking restart
                echo "set ok"
                IP_INPUT=1      
        }
        fi
}

echo "set IP into the main.cpp"
IP_INPUT=0

while [ $IP_INPUT -eq 0 ]
do
    echo "input IP"
    read set_IP -n

    if [[ $set_IP =~ ^([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5]).([0-9]{1,2}|1[0-9][0-9]|2[0-4][0-9]|25[0-5])$ ]]
    then    
        echo "input gateway"
        read GateWay
        
        arr_IP=${set_IP//./ }
        arr_IP=($arr_IP)
        arr_gw=${GateWay//./ }
        arr_gw=($arr_gw)
        
        for arr in 0 1 2
        do
            if [ ${arr_IP[$arr]} == ${arr_gw[$arr]} ]
            then
                echo "arr_IP:${arr_IP[$arr]}"
            else
                echo "error IP :$set_IP"
                continue 2
            fi
        done

        ping_func
    fi
done
    
    reboot_fun
原文地址:https://www.cnblogs.com/luoyankuan/p/10520639.html