shell编程之服务器IP地址一键修改

本shell脚本编程主要实现以下四个方面的功能:

1、实现将动态IP修改为静态IP

2、实现将静态IP修改为其他静态IP

3、实现修改之前确认是否修改,如果不修改需要恢复IP信息

4判断用户输入的IP是否正确,如果不正确,让其循环输入,直到正确输入为止

#!/bin/bash

#2020年2月24日20:36:07

#auto change server ip

########################

ETH_IP="$1"

ETH_NAME="ens33"

扫描二维码关注公众号,回复: 10752579 查看本文章

ETH_DNS="223.5.5.5"

ETH_MASK="255.255.255.0"

ETH_GATEWAY="192.168.1.254"

ETH_BAK="/data/backup/`date +%Y%m%d%H%M`"

ETH_DIR="/etc/sysconfig/network-scripts/"

function change_ip(){

cat > ifcfg-$ETH_NAME <<EOF

TYPE=Ethernet

BOOTPROTO=static

DEVICE=$ETH_NAME

ONBOOT=yes

IPADDR=$ETH_IP

NETMASK=$ETH_MASK

GATEWAY=$ETH_GATEWAY

DNS1=$ETH_DNS

EOF

cat ifcfg-$ETH_NAME

echo -e "\033[32mThe server ip change succeded.\033[0m"

}

if [ $# -eq 0 ];then

    echo -e "\033[32m------------------\033[0m"

    echo -e "\033[32mUsage:{/bin/sh $0 192.168.1.111|192.168.1.200|help}\033[0m"

    exit

fi

、、

checkip() 
{
   if echo $1 |egrep -q '^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$' ; then
      a=`echo $1 | awk -F. '{print $1}'`
      b=`echo $1 | awk -F. '{print $2}'`
      c=`echo $1 | awk -F. '{print $3}'`
      d=`echo $1 | awk -F. '{print $4}'`

   fi

    for n in $a $b $c $d; do
        if [ $n -ge 255 ] || [ $n -le 0 ]; then
            echo "the number of the IP should less than 255 and greate than 0"
        fi
    done

}

rs=1
while [ $rs -gt 0 ]; do
   read -p "Please input the ip:" ip
   checkip $ip
   rs=`echo $?`

done

echo "The IP is right!"

cd $ETH_DIR 

if [ ! -d $ETH_BAK ];then

    mkdir -p $ETH_BAK

fi

\cp ifcfg-$ETH_NAME $ETH_BAK

grep "dhcp" ifcfg-$ETH_NAME

if [ $? -eq 0 ];then

    change_ip

else

    echo -e "\033[32m------------------\033[0m" 

    cat ifcfg-$ETH_NAME

    read -p "The server static ipaddr already exist,please ensure change other static ip? " INPUT

    if [ $INPUT == "yes" -o $INPUT == "y" -o $INPUT == "Y" ];then

        change_ip

    fi

fi

read -p "The server ip change succeded,please restart network.service yes or no?" INPUT

if [ $INPUT == "yes" -o $INPUT == "y" -o $INPUT == "Y" ];then

    systemctl restart network.service

else

    \cp $ETH_BAK/ifcfg-$ETH_NAME $ETH_DIR/

    cat ifcfg-$ETH_NAME

fi

发布了14 篇原创文章 · 获赞 0 · 访问量 414

猜你喜欢

转载自blog.csdn.net/falnet/article/details/104487877