Skip to content

Instantly share code, notes, and snippets.

@ShahBinoy
Created October 3, 2016 20:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ShahBinoy/6841234478ac0e70be165b17d6b87b09 to your computer and use it in GitHub Desktop.
Save ShahBinoy/6841234478ac0e70be165b17d6b87b09 to your computer and use it in GitHub Desktop.
Discovers available IPs in AWS Subnets. Relies on default aws config
#!/bin/bash
while [[ $# -gt 1 ]]
do
key="$1"
case $key in
-s|--subnet)
SUBNETS="$2"
shift # past argument
;;
esac
shift # past argument or value
done
if [ -z "${SUBNETS}" ]; then
echo -n "Please provide subnet Ids [Comma Separated] : "
read ID_VAL < /dev/tty
else
ID_VAL="$SUBNETS"
fi
IFS=',' read -ra my_subnets <<< "$ID_VAL"
for subn in "${my_subnets[@]}"
do
cidr=$(aws ec2 describe-subnets --subnet-ids ${subn} | jq '.Subnets[].CidrBlock' | cut -d"\"" -f2)
echo " "
echo "Analyzing Subnet ${subn} with CIDR ${cidr}..."
echo "-------------------------------------------------------------"
all_ips=$(nmap -v -sn ${cidr} | grep "host down" | cut -d' ' -f5)
used_ips=$(aws ec2 describe-instances --filter Name="subnet-id",Values=\"${subn}\" | jq '.Reservations[].Instances[].PrivateIpAddress' | cut -d"\"" -f2)
echo "Used IPs: "
echo "---------"
printf '%s\n ' "${used_ips[@]}"
echo " "
echo "Available IPs:"
echo "--------------"
for del in ${used_ips[@]}
do
all_ips=(${all_ips[@]/$del})
done
printf '%s\n' "${all_ips[@]}"
used_ips=()
all_ips=()
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment