shell脚本+短语法来验证有效的IP

时间:2010-08-26 12:44:33

标签: bash

我的问题是,我希望得到一些简短明智的想法来验证IP地址然后我的例子

也许我可以在我的ksh脚本中组合一些perl语法

利迪娅

6 个答案:

答案 0 :(得分:1)

不要重新发明轮子。

use strict;
use warnings;
use Regexp::Common qw/net/;
# see http://search.cpan.org/dist/Regexp-Common/lib/Regexp/Common/net.pm

my $Address = '...';
# adapted from the module's synopsis
for ( $Address ) { 
    /$RE{net}{IPv4}/       and print "Dotted decimal IP address";
    /$RE{net}{IPv4}{hex}/  and print "Dotted hexadecimal IP address";
    /$RE{net}{IPv4}{oct}{-sep => ':'}/ and
                           print "Colon separated octal IP address";
    /$RE{net}{IPv4}{bin}/  and print "Dotted binary IP address";
    /$RE{net}{MAC}/        and print "MAC address";
    /$RE{net}{MAC}{oct}{-sep => " "}/ and
                           print "Space separated octal MAC address";
}

使用你需要的那个。

如果你无法安装模块,那么只需潜伏在模块的代码中并获得正确的正则表达式,具体取决于你想要匹配的IP地址类型。

或者,只要使用类似上面的内容,如果地址与您想要的任何符号相匹配,或者沿着这些符号,就调用相同的子。

从shell脚本中使用它将是:

return perl -e'use Regexp::Common qw/net/;$ip=shift;if ($ip =~ /$RE{net}{IPv4}/){exit 0}else{exit 1}' "$Address";

以上内容将取代您完整的“案例”区块。

同样,如果你需要在perl脚本调用中内联正则表达式,你可以通过阅读模块的代码来实现。

答案 1 :(得分:1)

check(){
  case "$1" in
     [0-9]|[0-9][0-9]|[0-1][0-9][0-9]|2[0-4][0-9]|25[0-5] ) echo "0";;
     *) echo "1";;
  esac
}
ip="$1"
OIFS="$IFS"
IFS="."
set -- $ip
result="$(check $1)$(check $2)$(check $3)$(check $4)"
case "$result" in
  "0000" ) echo "IP $ip Ok";;
  *) echo "IP $ip not ok";;
esac
IFS="$OLDIFS"

答案 2 :(得分:1)

在不触及IFS的情况下拆分地址,并通过按位移动避免复杂的检查:

declare -a part=( ${ip//\./ } )
declare -i valid=0

for p in ${part[@]}; do
  if [[ $p =~ ^[[:digit:]]+$ ]] ; then
    ((valid += p>>8 ))
  else
    ((valid++))
  fi
done

if [ $valid -eq 0 ] ; then
  echo -e "$ip     OK"
else
  echo -e "$ip NOT OK"
fi

答案 3 :(得分:0)

Bash> =版本3.2(这可以大大缩短):

valid () {
    if [[ $1 =~ ^[[:digit:]]+$ ]] && 
       (( $1 >= 0 && $1 <= 255 ))
    then
        echo "0"
        return 0
    else
        echo "1"
        return 1
    fi
}

saveIFS=$IFS
IFS='.'
ip=($1)
IFS=$saveIFS
for octet in ${ip[@]}
do
    if ! valid $octet > /dev/null
    then
        valid=1
    fi
done
[[ $valid != 1 ]] && echo "Good address" || echo "Bad address"

答案 4 :(得分:0)

这是一种更简单,更简单的方法。它只检查基本结构,但在某些情况下它就足够了。

VALID=$(echo $IP | egrep '^[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}$');

if [ ! -n "$VALID" ]; then
   echo "This IP ($IP) isn't valid. Please check it and try again.";
   exit 0;
fi;

答案 5 :(得分:0)

将ip地址保存到ip_server并使用以下代码进行检查:

if [[ "$ip_server" =~ ^([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})[.]([0-9]{1,3})$ ]]
then
    for (( i=1; i<${#BASH_REMATCH[@]}; ++i ))
    do
      (( ${BASH_REMATCH[$i]} &2; exit 1; }
    done
else
      echo "Wrong IP address" >&2
      exit 1;
fi
相关问题