scan all hosts in a list of subnets

1) Create a subnets.dat file with one subnet on each line:

$ cat subnets.dat
192.168.0.*
192.168.1.*

2) Run nmap with the subnets.dat file as input

$ nmap -sP -R -iL subnets.dat
Reading target specifications from FILE: subnets.dat

Starting nmap V. 3.00 ( www.insecure.org/nmap/ )
Host (192.168.0.0) appears to be down.
Host box1.mydomain.com (192.168.0.1) appears to be up.
Host box2.mydomain.com (192.168.0.2) appears to be down.
Host box3.mydomain.com (192.168.0.3) appears to be up.
Host (192.168.0.4) appears to be up.
...

Notice how names are resolved for existing hosts, but only an IP is returned, if there is no DNS record (e.g. 192.168.0.0).

3) Write a script to report on the output you want
e.g. for a list of all hosts that respond to ping

$ cat nmap_servers.sh
#!/bin/sh
OUTFILE=hosts_scanned.dat

# clean up old file
[ -f hosts_scanned.dat ] && rm hosts_scanned.dat
echo "nmap -sP -R -iL subnets.dat | grep "to be up" | awk '{print \$2}' "
echo ""

# write all hosts to file, but print only hosts that appear to be up.
nmap -sP -R -iL subnets.dat -oN $OUTFILE | grep "to be up" | awk '{print $2}'

Of course this output can always be redirected to a file, if desired. The output file "hosts_scanned.dat" will contain any host nmap found in DNS, and whether it was up or down.

----------
Sample output after grep and awk:
box1.mydomain.com
box3.mydomain.com
(192.168.0.4)

Notice that I use awk to print the second field. That's because some entries might have an IP address, but not a DNS entry. So the second field is whatever comes after Host, which is either an IP address, or a hostname. In this case, I want to find any IP's without hostnames, so I can fix DNS, but you may want to just keep the ip in the list,so you can ssh to it later.

To get rid of the parenthesis, I redirected the output to hosts_up.dat, and piped the output to grep and awk to illustrate:

cat hosts_up.dat | grep \( | awk -F[\(\)] '{print $2}

 

Article List