Using python nmap module to scan hosts generated from a previous scan

Arvandor picture Arvandor · Jul 16, 2014 · Viewed 15.4k times · Source

I've been playing with the module straight from the python command line to try and figure out how it all works, and start to piece together how the script I want to write is going to need to work. What I'd like to do, is do a simple host discovery scan first, such as -n -sP -PE, then use the all_hosts() function to generate the host list for the actual port scan. So if I do...

import nmap
nm = nmap.PortScanner()

nm.scan(hosts='XXX.XXX.XXX.X/24', arguments='-n -sP -PE')

Then nm.all_hosts() gives me exactly what I'm looking for, a shortened list of all the active hosts that the scan found. Now, the problem I'm having is passing that into the next scan. If you just do something like

hostlist = nm.all_hosts()
nm.scan(hosts=hostlist etc)

Then it complains about not being able to use a list for the hosts argument. Ok, makes sense. So I tried to make it comma separted, so they'd show up as aaa.aaa.aaa.aaa, bbb.bbb.bbb.bbb etc, by doing...

hostlist = ""
for item in nm.all_hosts():
    hostlist = item + ", " + hostlist

Then, just dumping hostlist, it looks just how I'd like it to, but if you try to plug that into the hosts argument, it says "Failed to resolve "alltheipslisted" WARNING: No targets were specified, so 0 hosts scanned.

Does anyone have any good ideas for how to go about this? Maybe dumping the IPs to then pulling them from a file? Seems like I'd run into the same problem if a string isn't working...

Answer

dwitvliet picture dwitvliet · Jul 16, 2014

If you remove the comma it will work. Multiple hosts are listed with only a space between them.

Example of use:

import nmap
nm = nmap.PortScanner()

hostlist = ' '.join(nm.all_hosts())
nm.scan(hosts=hostlist, arguments='-n -sP -PE')