Free IP address script

We frequently have to assign static IP addresses to servers and certain workstations. Although the following script does not guarantee that the IPs returned are not currently in use or are reserved for future use, it performs the following checks:

* ICMP ECHO REQUEST (ping)
* DNS PTR (reverse) lookup
* TCP Connect scan using nmap for common services

If an IP address does not respond to a ping, does not have a DNS PTR record, and is not listening for common services, it is considered available for assignment.

#!/bin/sh

# For each of the IPs specified, try an ICMP ECHO REQUEST (ping),
# reverse DNS (PTR) lookup, and port scan for open $SERVICES.
# If the host does not respond to a ping, has no DNS PTR entry,
# and does not have open ports listed in the $SERVICES variable,
# it is considered available for assignment.

if [ -z $@ ] ; then
   echo "  Usage: ./free_ips.sh {IP_range}"
   echo "Example: ./free_ips.sh 192.168.1.1-100"
   exit 1
fi

# SERVICES is the list of ports to scan on the host
SERVICES=21,22,23,25,53,80,137,138,139,443,445

for i in `nmap -sP -v $1 | grep down | awk '{print $2}' | tr -d '()'`
do
   # Does a DNS PTR record exist?
   dig -x $i | grep NXDOMAIN > /dev/null 2>&1
   if [ $? -eq 0 ] ; then
      # Are any of the ports listed in $SERVICES open?
      nmap -P0 -p $SERVICES -T Aggressive $i | grep open > /dev/null 2>&1
      if [ $? -eq 1 ] ; then
         echo $i
      fi
   fi
done

Back to brandonhutchinson.com.

Last modified: 05/08/2003