Skip to main content

ResolveIPstoSubnets.sh

#!/bin/bash

# Input and output files
INPUT_FILE="hosts.txt" # File containing hostnames or IPs (one per line)
OUTPUT_FILE="subnets_summary.txt"

# Initialize an empty array to store subnets
declare -A subnets

# Loop through each line in the input file
while IFS= read -r entry || [[ -n "$entry" ]]; do
# Skip empty lines
[[ -z "$entry" ]] && continue

# Perform nslookup
IP=$(nslookup "$entry" 2>/dev/null | awk '/^Address: / { print $2 }' | tail -n 1)

if [[ -n "$IP" ]]; then
# Extract the subnet (using /24 by default)
SUBNET=$(echo "$IP" | awk -F. '{ printf "%s.%s.%s.0/24\n", $1, $2, $3 }')
subnets["$SUBNET"]=1
echo "Resolved $entry to $IP, Subnet: $SUBNET"
else
echo "Failed to resolve $entry" >&2
fi
done < "$INPUT_FILE"

# Write unique subnets to the output file
echo "Subnets in scope:" > "$OUTPUT_FILE"
for subnet in "${!subnets[@]}"; do
echo "$subnet" >> "$OUTPUT_FILE"
done

echo "Subnet summary saved to $OUTPUT_FILE."