Created
February 5, 2016 13:59
-
-
Save smbambling/0954c70e032695ecc59f to your computer and use it in GitHub Desktop.
Find available IP addresses using DNS and DIG ( -x axfr )
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
#!/usr/bin/env bash | |
# Find available IP addresses from by using dig -x axfr | |
usage() { | |
cat <<-EOF | |
usage: ${0} <network> | |
example: ${0} 10.1.10 | |
EOF | |
} | |
declare -r network=$1 | |
if [ -z "${network}" ]; then | |
echo "ERROR: No network provided" | |
usage | |
exit 1 | |
fi | |
# Reference Commands | |
cmd_list='dig sort awk' | |
# Function to check if referenced command exists | |
cmd_exists() { | |
if [ $# -eq 0 ]; then | |
echo 'No command argument was passed to verify exists' | |
exit 1 | |
fi | |
cmd=${1} | |
cmd_fullpath=$(which "${cmd}") | |
if [ ! -x "${cmd_fullpath}" ]; then | |
echo "${cmd} command not found" | |
exit 1 | |
#else | |
# echo "Found: ${cmd} at ${cmd_fullpath}" | |
fi | |
} | |
# Verify that referenced commands exist on the system | |
for cmd in ${cmd_list}; do | |
cmd_exists "$cmd" | |
done | |
# Reference: http://stackoverflow.com/questions/15867557/finding-gaps-sequential-numbers | |
# Explanation of [ awk '$1!=p+1{print p+1"-"$1-1}{p=$1}' ] | |
# * $1 is the first column from current input line | |
# * p is the previous value of the last line | |
# * so ($1!=p+1) is a condition : if $1 is different than previous value +1, then : | |
# * this part is executed : {print p+1 "-" $1-1} : print previous value +1, the - character and fist columns + 1 | |
# * {p=$1} is executed for each lines : p is assigned to the current 1st column | |
available_ips=$(dig -x "${network}" axfr | sort -k 1 -n -u | awk -F'.' '/^[0-9]/ { print $1 }' | awk '$1!=p+1{print p+1"-"$1-1}{p=$1}') | |
for i in ${available_ips}; do | |
seq1=$(echo "${i}" | cut -d'-' -f1) | |
seq2=$(echo "${i}" | cut -d'-' -f2) | |
if [ "${seq1}" == "${seq2}" ]; then | |
echo "${network}.${seq1}" | |
else | |
echo "${network}.${i}" | |
fi | |
done |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment