我有 2 个列表,一个包含所有 32 位 IP 地址,另一个是 IP 范围和其他 IP 地址的列表。我需要查找列表 A 中的每个 IP 是否存在于列表 B 中的任何 IP 范围或地址中。最终结果将是显示列表 A 中不存在于列表 B 中的地址。如果 IP范围不涉及。该列表本身包含近 10,000 行,因此手动完成此操作将花费很长时间。
答案1
这个脚本可以在 Linux/Bash 上发挥作用。我不确定它是否没有错误。如果您需要任何解释,请评论。
#!/bin/bash
# The script prints addresses from one file that are NOT
# in the ranges provided in another file.
# $1 is the file with addresses to check
# $2 is the file that holds the ranges
## in format x.x.x.x-y.y.y.y or as a single IP, one per line.
### Variables ###
inFile="$1"
rangesFile="$2"
typeset -a rangesLow rangesHigh #arrays of int
rangesCount=
### Functions ###
toInt () {
printf "%d\n" $(($1*256*256*256 + $2*256*256 + $3*256 + $4))
}
readRanges () {
while IFS=- read -a range
do
IFS=. read -a low <<< "${range[0]}"
[ -z "${range[1]}" ] && range[1]="${range[0]}"
IFS=. read -a high <<< "${range[1]}"
rangesLow+=( $(toInt "${low[@]}") )
rangesHigh+=( $(toInt "${high[@]}") )
done < "$rangesFile"
rangesCount=${#rangesLow[@]}
}
singleCheck () {
# $1 is the address to check.
# $2 and $3 are the bounds, low and high.
# Returns 0 if NOT in range.
[[ $1 -ge $2 ]] && [[ $1 -le $3 ]] && return 1
# To invert the logic of the script, instead of the line above
## use this one:
# [[ $1 -ge $2 ]] && [[ $1 -le $3 ]] || return 1
return 0
}
addressCheck () {
# The function takes in 4 octets of an IP as four positional parameters.
# Returns 1 if IP is in any range.
# If not in range, the address is printed to stdout.
local address
address=$(toInt "$@")
for ((i=0; i<rangesCount ; i++)) # Loop for all ranges.
do
singleCheck "$address" "${rangesLow[$i]}" "${rangesHigh[$i]}" || return 1
done
printf "%d.%d.%d.%d\n" "$@"
}
checkAll () {
while IFS=. read -a toCheck
do
addressCheck "${toCheck[@]}"
done < "$inFile"
}
main () {
readRanges
checkAll
}
### Execute ###
main
基于海米的绝妙思想。
答案2
我不知道 shell 脚本,但程序应该能够将两个列表从点分四组 IP 地址转换为单个整数,然后将数字与标准大于小于进行比较。
i = (first octet * 256*256*256) + (second octet * 256*256)
+ (third octet * 256) + (fourth octet)