For those of you who have worked with NMMAP before, Im raising an error each time I run my script. I'm using <python3 nmap_scanner.py -H 10.50.60.125 -p 21, 1720> at the command line to execute the script, and im running into the error:

Traceback (most recent call last):
  File "nmap_scanner.py", line 33, in <module>
    main() 
  File "nmap_scanner.py", line 30, in main
    nmapScan(tgtHost, tgtPort)
  File "nmap_scanner.py", line 10, in nmapScan
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
  File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/site-packages/nmap/nmap.py", line 469, in __getitem__
    return self._scan_result['scan'][host]
KeyError: '10.50.60.125'


import nmap 
import optparse 

def nmapScan(tgtHost, tgtPort):
        nmScan = nmap.PortScanner()
        nmScan.scan(tgtHost, tgtPort) 
        state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
        print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state)

def main():
    parser = optparse.OptionParser("usage%prog " + \
                                    "-H <target host> -p <target port>") 

    parser.add_option('-H', dest='tgtHost', type='string', \
                        help='specify target host') 

    parser.add_option('-p', dest='tgtPort', type='string', \
                        help='specify target port[s] seperated by comma') 

    (options, args) = parser.parse_args() 
    tgtHost = options.tgtHost
    tgtPorts = str(options.tgtPort).split(', ') 
    if (tgtHost == None) | (tgtPorts[0] == None):
        print(parser.usage)
        exit(0)
    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)

if __name__ == "__main__":
    main() 

It means the scan was unsuccessful (probably because it can't connect). Running your script like nmapScan("127.0.0.1", "22") brought up results, but running it on "123.565.343.22" (a bogus ip i just made up) brought a Key error. You could catch this with a try block:

try:
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
    print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state)
except KeyError as exkey:
    print("[!] Cannot scan host!: " + tgtHost)

If the IP is good, then your problem lies elsewhere. The script is okay, but you might want to catch that error and return some result stating that it cant scan.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.