我现在的剧本:
#!/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地址范围的最佳方法是什么?
发布于 2013-04-11 18:22:07
如果您只想检查IP地址是否有效,可以在bash中使用ipcalc命令来检查这个地址。
ipcalc -c $userinput
example
ipcalc -c 10.20.30.401
ipcalc: bad IPv4 address: 10.20.30.401发布于 2013-02-07 12:57:22
可能不是最好的解决方案,但作为对脚本的快速修复,应该这样做:
#!/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地址可以是硬编码的,也可以是从其他地方获取的,但是我把它与参数验证和错误检查一起留给您。
发布于 2022-12-04 15:52:24
对于Ubuntu:
sudo apt install grepcidr ipcalc然后:
RANGE="192.168.1.210-192.168.1.250"
IP="192.168.1.250"
grepcidr "$(ipcalc -r "$RANGE" | tail -n+2)" <(echo "$IP") >/dev/null && echo "in" || echo "out"https://stackoverflow.com/questions/14751293
复制相似问题