2013-02-07 83 views
0

我当前的脚本:读取IP地址和/检查是否有效范围之间

#!/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.XXX范围内,我已经尝试使用:

8 *
80 *
80. *

但它总是有错误:

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

什么是定义一系列的IP地址小于(LT)和GT(大于)的最好方法?

+0

不要隐藏您在变量中运行的命令。它使得你的代码不易读,并且不能像你认为的那样频繁工作。只需输入'vps $ userinput | grep ...' – chepner

+0

好的,这是有道理的,但我怎么从一个if循环中整齐地调用它呢? – Zippyduda

回答

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 

编辑:一个更好的解决方案将采取所有三个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地址,而不是一个像以前一样。当然,最低和最高的IP地址可以是硬编码的或从其他地方获取,但我将其与参数验证和错误检查一起留给您。

+0

这工作,谢谢:)理想情况下,它会查看整个IP地址,并检查它是否在我有范围列表。有10个独特的范围仅在第3和第4个八位字节上有所不同。 – Zippyduda

+0

使用'IFS =“。”读-a八位位组<<< $ userinput'。然后分别检查每个'$ {octets [0]}','$ {octets [1]}'等。 – chepner

+0

@Zippyduda答案更新更灵活。 – KBart

2

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

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