Akshay Akshay - 6 months ago 41
Python Question

Using nmap library in Python program

I have a simple Python program which uses nmap library to do port scanning.

from optparse import OptionParser
import nmap
from threading import *

screenLock=Semaphore(value=1)

def nmapScan(thost,tport):
x=nmap.PortScanner()
x.scan(thost,tport)
state=x[thost]['tcp'][int(tport)]['state']
print "[*]" + thost + "tcp/"+tport+" "+state


def main():
parser=OptionParser('usage %prog -H <target host> -p <target port>')
parser.add_option('-H',dest='thost',type='string',help='specify target host')
parser.add_option('-p',dest='tports',type='string',help='specify target port[s] seperated by comma')
(options,args)=parser.parse_args()
thost=options.thost
tports=options.tports
tports=tports.split(',')
if (thost==None)|(tports==None):
print parser.usage
exit(0)
for i in tports:
nmapScan(thost,i)

main()


When i run the program, i get the following error.

akshayrajmacbookpro$ python nmapScanner.py -H 192.168.1.60 -p 80,443
Traceback (most recent call last):
File "nmapScanner.py", line 28, in <module>
main()
File "nmapScanner.py", line 26, in main
nmapScan(thost,i)
File "nmapScanner.py", line 10, in nmapScan
state=x[thost]['tcp'][int(tport)]['state']
File "build/bdist.macosx-10.11-intel/egg/nmap/nmap.py", line 555, in __getitem__
KeyError: '192.168.1.60'


I tried using url instead of ip in the command line. But I get the same error. Being new to Python, I am not able to understand and resolve this.

Answer

x (instance of nmap.PortScanner) does not contain those keys. To be able to iterate the scan results you can do this:

for host, result in x._scan_result['scan'].items():
    print "[*]" + thost + "tcp/" + tport + " " + result['status']['state']

It's best if you looked at the docs or source code of python-nmap to see what other useful info is available e.g. Service name and version that is listening on that port.

More info here: https://bitbucket.org/xael/python-nmap/src/f368486a2cf12ce2bf3d5978614586e89c49c417/nmap/nmap.py?at=default&fileviewer=file-view-default#nmap.py-381

Comments