[python]Intrusive python with nmap

So i was trying some simple script to invoke nmap with python. So here is a python command line version.
The python script takes in two types of arguments:
a. target host
b. target port/ports.

the port if more than one should separate by commas. The split method is called to put each port into an array dports

So here’s the code sample:

import nmap
from optparse import OptionParser

def nmapScan(dhost,dport):
    nm = nmap.PortScanner()
    state = nm[dhost]['tcp'][int(dport)]['state']
    print("[*] " + dhost + " " + "tcp/"+dport + " " + state)

def main():
    parser = OptionParser(usage='usage: %prog -d <destination host> -p <destination port separated by commas>')
    parser.add_option('-d', dest='dhost', type='string', help='specify target host')
    parser.add_option('-p', dest='dport', type='string', help='specify target port separated by commas')
    (options, args) = parser.parse_args()
    dhost = options.dhost
    #split(",") not split(", "), the latter will cause python3 to give an error like this
    #ValueError: invalid literal for int() with base 10:
    dports = str(options.dport).split(",")
    if(dhost == None) | (dports == None):
    for dport in dports:

if __name__ == '__main__':

If there is no argument specified the result looks like this:

Usage: nmap2.py -d -p

-h, --help show this help message and exit
-d DHOST specify target host
-p DPORT specify target port separated by commas

Another scenario is specify one host and one port for nmap scan:

Cyruss-Air:net1 cyruslok$ sudo python3 nmap2.py -d -p22
[*] tcp/22 open

Another scenarios is to specifiy more than one port for nmap scan:

Cyruss-Air:net1 cyruslok$ sudo python3 nmap2.py -d -p21,22,23,80,443
[*] tcp/21 closed
[*] tcp/22 open
[*] tcp/23 closed
[*] tcp/80 closed
[*] tcp/443 closed


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s