Created
August 8, 2024 14:42
-
-
Save socketbox/376b887f311dea89ecd9f58d983e390f to your computer and use it in GitHub Desktop.
A script that takes two files--a set of IPs and a set of Subnet--and shows which IPs are in which subnets
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
if [ "$#" -lt 2 ]; then | |
echo "Usage: $0 <IP_FILE> <CIDR_FILE>" | |
exit 1 | |
fi | |
IP_FILE=$1 | |
CIDR_FILE=$2 | |
# Read IPs and subnets into arrays | |
mapfile -t ips < "$IP_FILE" | |
mapfile -t subnets < "$CIDR_FILE" | |
# Function to check if an IP is in a subnet | |
check_ip_in_subnet() { | |
local ip=$1 | |
local subnet=$2 | |
local temp_subnet_file=$(mktemp) | |
echo "$subnet" > "$temp_subnet_file" | |
if echo "$ip" | iprange -1 "$temp_subnet_file" &>/dev/null; then | |
rm "$temp_subnet_file" | |
return 0 | |
else | |
rm "$temp_subnet_file" | |
return 1 | |
fi | |
} | |
# Check each IP against the subnets | |
for ip in "${ips[@]}"; do | |
found=0 | |
for subnet in "${subnets[@]}"; do | |
if check_ip_in_subnet "$ip" "$subnet"; then | |
echo "IP address $ip is in subnet $subnet" | |
found=1 | |
break | |
fi | |
done | |
if [ "$found" -eq 0 ]; then | |
echo "IP address $ip is not in any of the subnets" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment