判断IP是否规范并添加或修改IP地址的shell脚本

被刻印的时光 ゝ 提交于 2019-12-25 21:17:12

.

#!/bin/bash
read -p "请输入ip:" IP
read -p "请输入掩码:" MASK

#read -p "IP ADDRESS:" IPADD
echo $IP > /tmp/tmpserverip
echo $IP | grep "^[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}\.[0-9]\{1,3\}$" > /dev/null
if [ $? = 1 ]
then
  echo "error ip,please enter correct"
  exit 1
else
  a=`awk -F. '{print $1}' /tmp/tmpserverip`
  b=`awk -F. '{print $2}' /tmp/tmpserverip`
  c=`awk -F. '{print $3}' /tmp/tmpserverip`
  d=`awk -F. '{print $4}' /tmp/tmpserverip`
    if [ $a -ge 255 ]||[ $a -le 0 ]
    then
      echo "a:error ip"
      exit 1
    else
      echo a > /tmp/tang
    fi

    if [ $b -ge 255 ] || [ $b -lt 0 ]
    then
      echo "b:error ip"
      exit 1
    else
      echo b >> /tmp/tang
    fi

    if [ $c -ge 255 ] || [ $c -lt 0 ]
    then
      echo "c:error ip"
      exit 1
    else
      echo c >> /tmp/tang
    fi
    if [ $d -ge 255 ] || [ $d -le 0 ]
    then
      echo "d:error ip"
      exit 1
    else
      echo d >> /tmp/tang
    fi
fi

sed -i "s/ONBOOT=no/ONBOOT=yes/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i "s/BOOTPROTO=dhcp/BOOTPROTO=static/g" /etc/sysconfig/network-scripts/ifcfg-eth0
sed -i 's/NM_CONTROLLED=yes/NM_CONTROLLED=no/g' /etc/sysconfig/network-scripts/ifcfg-eth0
grep IPADDR /etc/sysconfig/network-scripts/ifcfg-eth0 &> /dev/null
if [ $? -eq 0 ]
then
  sed -i "s/IPADDR=*.*.*.*/IPADDR=$IP/g" /etc/sysconfig/network-scripts/ifcfg-eth0
  sed -i "s/NETMASK=*.*.*.*/NETMASK=$MASK/g" /etc/sysconfig/network-scripts/ifcfg-eth0
else
  echo "IPADDR=$IP" >> /etc/sysconfig/network-scripts/ifcfg-eth0
  echo "NETMASK=$MASK" >> /etc/sysconfig/network-scripts/ifcfg-eth0
fi

/etc/init.d/network restart

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!