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

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

import nmap 
import optparse 

def nmapScan(tgtHost, tgtPort):
        nmScan = nmap.PortScanner()
        nmScan.scan(tgtHost, tgtPort) 
        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):
    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)

if __name__ == "__main__":

It means the scan was unsuccessful (probably because it can't connect). Running your script like nmapScan("", "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:

    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.