1

In nmap command line, we can provide list of hosts in file and the file can be provided as an input using -iL parameter. I am not sure how to replicate the same function using python nmap. Python nmap documentation is not covering all examples. So requiring help in it.

2 Answers2

3

You can use the -iL option as given below. It worked for me.

nm.scan(arguments='-iL /tmp/hosts.txt')

Full program given below

import sys
import os

import nmap                         # import nmap.py module
try:
    nm = nmap.PortScanner()         # instantiate nmap.PortScanner object
except nmap.PortScannerError:
    print('Nmap not found', sys.exc_info()[0])
    sys.exit(1)
except:
    print("Unexpected error:", sys.exc_info()[0])
    sys.exit(1)

nm.scan(arguments='-iL /tmp/hosts.txt')

for host in nm.all_hosts():
    print('----------------------------------------------------')
    print('Host : %s (%s)' % (host, nm[host].hostname()))
    print('State : {0}'.format(nm[host].state()))


# print result as CSV
print(nm.csv())
Ameen Ali Shaikh
  • 409
  • 1
  • 3
  • 10
0

I don't think that python-nmap supports target lists out of the box. You will probably need to use python to open and parse the list yourself, and then execute the scans in a loop. I will probably look something like this:

import nmap
nm = nmap.PortScanner() 
port_range='22'   
with open('./path/to/list', 'r') as targets:
    for target in targets:
        nm.scan(target, port_range)
        # Do something with results 
  • It does support lists / or multiple hosts in one call space separated -> see answer here https://stackoverflow.com/a/24785751/478656 and looks like you may be able to specify `-iL` in the arguments, if it will let you provide empty hosts. – TessellatingHeckler Mar 05 '19 at 06:36
  • That's pretty handy. It might hurt the readability of the script if you do something like that however, so I'd probably still recommend pulling the file into your script and going from there. – Buffersandbeer Mar 05 '19 at 06:46