Inputting range of ports with nmap & optparser

2019-09-19 10:46发布

问题:

This is the script

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('-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] separated 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()

When I try to enter a range of ports in the command line, I get this error. Could someone help me out? I'm a newbie to python. Thanks in advance!!

    :~$ python nmapScan.py -H 192.168.1.6 -p 20-25
Traceback (most recent call last):
  File "nmapScan.py", line 27, in <module>
    main()
  File "nmapScan.py", line 23, in main
    nmapScan(tgtHost, tgtPort)
  File "nmapScan.py", line 7, in nmapScan
    state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
ValueError: invalid literal for int() with base 10: '20-25'

回答1:

You need to distinguish between those two different formats, and if the m-n range format is used, split at '-' to get the boundaries, create the list of port using range(), and set tgtPorts to that range.

Here's a function to implement this. You can simply plug it into your code by doing

tgtPorts = parse_port_spec(options.tgtPort)

instead of your current tgtPorts = str(options.tgtPort).split(','):

def parse_port_spec(spec):
    if ',' in spec:
        # Port list
        ports = spec.split(',')
    elif '-' in spec:
        # Port range
        start, end = map(int, spec.split('-'))
        ports = range(start, end + 1)
    else:
        # Single port
        ports = [spec]
    return map(int, ports)

Note however that this still does not support the full nmap port range specification syntax. You can only use a comma separated list, or a range defined by m-n, but not both.

See the documentation for range() and map() for details on how those functions work.



回答2:

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('-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] separated by comma')
    (options, args) = parser.parse_args()
    if not options.tgtHost or not options.tgtPort:
        print parser.usage
        exit(0)
    tgtHost = options.tgtHost
    ports = options.tgtPort
    tgtPorts = options.tgtPort.split(',') if "," in options.tgtPort else map(str,range(int(ports.split("-")[0]),int(ports.split("-")[1]+1))) 
    for tgtPort in tgtPorts:
        nmapScan(tgtHost, tgtPort)
if __name__ == '__main__':
    main()

Like I said in a comment you should really use some try/excepts to avoid your script crashing.

~$ python nm.py -H 10.10.10.100 -p 20-25
[*] 10.10.10.100  tcp/20 closed
[*] 10.10.10.100  tcp/21 closed
[*] 10.10.10.100  tcp/22 open
[*] 10.10.10.100  tcp/23 closed
[*] 10.10.10.100  tcp/24 closed

$ python nm.py -H 10.10.10.100  -p 20,21
[*] 10.10.10.100  tcp/20 closed
[*] 10.10.10.100  tcp/21 closed

~$ python nm.py -H 10.10.10.100 
-H <target host> -p <target port>

As per the documentation you can use nmap.PortScanner() which takes a string in the form 20-25 for a range which you could just use that in your script, parse the dict to get the output and make your life easier:

In [7]: import nmap

In [8]: nm = nmap.PortScanner()

In [9]: nm = nmap.PortScanner()

In [10]: nm.scan('127.0.0.1', '20-25')

We can shorten your script using the proper nmap syntax:

import nmap
import optparse

def main():
    parser = optparse.OptionParser('-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] separated by comma')
    (options, args) = parser.parse_args()
    if not options.tgtHost or not options.tgtPort:
        print parser.usage
        exit(0)
    tgtHost = options.tgtHost
    tgtPorts = options.tgtPort

    nm = nmap.PortScanner()
    res = nm.scan(tgtHost,tgtPorts)
    for port in nm[tgtHost]["tcp"].keys():
        print "[*]  {} tcp/{} {}".format(tgtHost,port,res["scan"][tgtHost]["tcp"][int(port)]["state"])

if __name__ == '__main__':
    main()


~$ python nm.py -H 10.10.10.100 -p 20-25
[*]  10.10.10.100  tcp/20 closed
[*]  10.10.10.100  tcp/21 closed
[*]  10.10.10.100  tcp/22 open
[*]  10.10.10.100  tcp/23 closed
[*]  10.10.10.100  tcp/24 closed
[*]  10.10.10.100  tcp/25 open