读取IP地址并检查是否有效/在范围之间

时间:2013-02-07 12:36:37

标签: bash loops if-statement ip-address

我目前的剧本:

#!/usr/local/bin/bash
echo -n "Enter VPS IP address:"
read userinput
lookupip="vps $userinput"

if [[ $userinput -lt 80.* || $userinput -gt 255.* ]] #checks input is in the range
 then
   echo "Input outside acceptable range."
 else

#The grep removes all from VPS tool output except primary IP address

$lookupip | grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' | sed '1 ! d' | xargs ping -oc 1000 -Q

fi

最低IP地址范围是80.X.X.X范围,我尝试过使用:

8 *
80 *
80. *

但它总是错误:

line 10: [[: 80.X.X.X: syntax error in expression (error token is ".X.X.X")

定义小于(lt)和gt(大于)的IP地址范围的最佳方法是什么?

2 个答案:

答案 0 :(得分:2)

如果您只是想检查IP地址是否有效,可以在bash中使用ipcalc命令来检查。

ipcalc -c $userinput
example
ipcalc -c 10.20.30.401
ipcalc: bad IPv4 address: 10.20.30.401

答案 1 :(得分:1)

可能不是最佳解决方案,但作为脚本的快速修复应该:

#!/usr/local/bin/bash
echo -n "Enter VPS IP address:"
read userinput
lookupip="vps $userinput"
first_octet=`echo "$userinput" | cut -d'.' -f1`

if [[ $first_octet -lt 80 || $first_octet -gt 255 ]]
 then
   echo "Input outside acceptable range."
 else

#The grep removes all from VPS tool output except primary IP address

$lookupip | grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' | sed '1 ! d' | xargs ping -oc 1000 -Q

fi

EDITED:一个更好的解决方案将所有三个IP地址(一个被检查,最低和最高)作为参数,将它们转换为32位数(这就是inet_aton()函数并检查范围:

#!/usr/local/bin/bash

inet_aton ()
{
    local IFS=. ipaddr ip32 i
    ipaddr=($1)
    for i in 3 2 1 0
    do
        (( ip32 += ipaddr[3-i] * (256 ** i) ))
    done

    return $ip32
}

echo -n "Enter VPS IP address, min IP address, max IP address:"
read userinput

ip1=`echo "$userinput" | cut -d' ' -f1`
ip2=`echo "$userinput" | cut -d' ' -f2`
ip3=`echo "$userinput" | cut -d' ' -f3`

lookupip="vps $ip1"

ip=`inet_aton $ip1`
min=`inet_aton $ip2`
max=`inet_aton $ip3`

if [[ $ip -lt $min || $ip -gt $max ]]
 then
   echo "Input outside acceptable range."
 else

#The grep removes all from VPS tool output except primary IP address

$lookupip | grep -E -o '(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' | sed '1 ! d' | xargs ping -oc 1000 -Q

fi

唯一的区别是你必须输入3个IP地址,而不是像以前那样输入3个IP地址。当然,最低和最高的IP地址可以是硬编码的,也可以从其他地方获取,但我将其与参数验证和错误检查一起留给您。