我需要检查 IP 地址或网络是否包含在其他网络中,例如“10.1.2.3”是否在“10.0.0.0/8”中,或者“10.1.2.0/24”是否在“10.0.0.0/”中8'。目前我使用 python 来实现此目的,例如:
if [ $(python -c 'import ipaddress; print(ipaddress.ip_address("10.1.2.3") in ipaddress.ip_network("10.0.0.0/8"))') == "True" ]; then
echo "10.1.2.3 is in network 10.0.0.0/8"
fi
在 Bash 中是否有更简洁/有效的方法来做到这一点?
答案1
这是不那么简洁的 bash 脚本:
#!/bin/bash
v4dec() {
for i; do
echo $i | {
IFS=./
read a b c d e
test -z "$e" && e=32
echo -n "$((a<<24|b<<16|c<<8|d)) $((-1<<(32-e))) "
}
done
}
v4test() {
v4dec $1 $2 | {
read addr1 mask1 addr2 mask2
if (( (addr1&mask2) == (addr2&mask2) && mask1 >= mask2 )); then
echo "$1 is in network $2"
else
echo "$1 is not in network $2"
fi
}
}
v4test 10.1.2.3 10.0.0.0/8
v4test 10.1.2.0/24 10.0.0.0/8
v4test 192.168.0.1 10.0.0.0/8
v4test 10.0.0.0/7 10.0.0.0/8
输出:
10.1.2.3 is in network 10.0.0.0/8
10.1.2.0/24 is in network 10.0.0.0/8
192.168.0.1 is not in network 10.0.0.0/8
10.0.0.0/7 is not in network 10.0.0.0/8
答案2
用于对网络中的 ip 地址执行此操作的 awk 脚本。我想网络部分还需要更多的网络。
ipcalc -b 10.0.0.0/8 |awk -f check_ip.awk ip="10.1.2.3"
ip is in range
脚本 -
{
if ($1 == "HostMin:") {
split($2,add_min,".")
} else if ($1 == "HostMax:") {
split($2,add_max,".")
}
}
END{
split(ip, ip_addr, ".")
found = 1
for(i=1; i<=4; i++) {
if (ip_addr[i] < add_min[i] || ip_addr[i] > add_max[i]) {
found = 0
break
}
}
if (found)
print "ip is in range"
else
print "ip is Not in range"
}