[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()
    nm.scan(dhost,dport)
    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):
        parser.print_help()
        exit(0)
    for dport in dports:
        nmapScan(dhost,dport)

if __name__ == '__main__':
    main()

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

Usage: nmap2.py -d -p

Options:
-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 192.168.1.150 -p22
[*] 192.168.1.150 tcp/22 open

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

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

Advertisements
This entry was posted in Python, Scripting and tagged , , . Bookmark the permalink.

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s