我有 2 個列表,一個包含所有 32 位元 IP 位址,另一個是 IP 範圍和其他 IP 位址的列表。我需要查找清單 A 中的每個 IP 是否存在於清單 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)