Signup/Sign In

Nmap Port Scanning script with input from Command Line

In this tutorial we will learn taking input from command line while running the script, rather than hardcoding the values in the script. we will look at two different ways to take input from command line:

  • using argparse
  • using optparse

Parsing arguments using argparse

scan_nmap.py

#!usr/bin/evn python
#Integrating nmap

import nmap
import argparse

# defining nmap scan function with arguments
# tgtHost will hold the host value and tgtPort will hold the port value
def nmapScan(tgtHost, tgtPort):
    nmscan = nmap.PortScanner()
    nmscan.scan(tgtHost, tgtPort)
    state = nmscan[tgt_host]['tcp'][int(tgtPort)]['state']
    print " [*] " + tgtHost + " tcp/"+tgtPort + " "+state

def main():
    # setup argument parsing
    parser = argparse.ArgumentParser(description='Command line Argument passing example')
    
    # reading and storing the value for host
    parser.add_argument('--host', action = "store", dest = "host",
    required=True)

    # reading and storing the value for port
    parser.add_argument('--port', action = "store", dest = "port", 
    type = int, required = True)

    given_args = parser.parse_args()
    tgtHost = given_args.host
    tgtPort = given_args.port

    #check if host and port values are not null
    if (tgtHost == None) | (tgtPort == None):
        print parser.usage
        exit(0)
    else:
        print "Scanning: " + tgtHost + "-" + str(tgtPort)
        # calling the nmapScan function with the provided values
        nmapScan(tgtHost, str(tgtPort))

if __name__ == '__main__':
    main()

In the above script, nmapScan is a simple method, which takes in two arguments, the host name/address and the port number which you want to scan.

In the main() function, we are using the argparse to parse the arguments provided while the script is run. The add_argument(), parses the arguments and save their values.

while running this program, you can only specify one port at once like:

python scan_nmap.py  --host=127.0.0.1  --port=21

[*] 127.0.0.1 tcp/21 closed

So if you want to scan 10 ports for a particular host, you need to run the script 10 times. We don't want that! So, now we will see a different way to accomplish this. Here we will pass ports as a string separated by comma, like '21, 80, 23' (with quotes).


Parsing arguments using optparse

scanner.py

#!usr/bin/evn python
#Integrating nmap

import nmap
import optparse

# defining nmap scan function with arguments
# tgtHost will hold the host value and tgtPort will hold the port value
def nmapScan(tgtHost, tgtPort):
    nmscan = nmap.PortScanner()
    nmscan.scan(tgtHost, tgtPort)
    state = nmscan[tgt_host]['tcp'][int(tgtPort)]['state']
    print " [*] " + tgtHost + " tcp/"+tgtPort + " "+state

def main():
    # printing Help to inform How to use this script
    parser = optparse.OptionParser('Script Usage:'+'-H <target host> -p <target port>')
    
    parser.add_option('-H', dest='tgt_Host', type='string', 
    help='specify target host')

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

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

if __name__ == '__main__':
        main()

You will see that optparse and argparse also differs in terms of the style of passing the argument while the script is run.

Other than that, we can use argparse for taking the comma separated list of ports as an input and then running a for loop to scan each port.

But our motive here was to provide you with two different ways, to do the same thing. As a result, now you know, how to use optparse and argparse. Using these, you can even write simple python scripts for various operations.

To run the above script:

python scanner.py  -H 127.0.0.1  -p '21,23,80'

[*] 127.0.0.1 tcp/21 closed [*] 127.0.0.1 tcp/23 closed [*] 127.0.0.1 tcp/80 open


Taking Input from Command Line for a python script using argparse and optparse