Inputting range of ports with nmap optparser

2024/10/9 3:19:15

This is the script

import nmap
import optparsedef nmapScan(tgtHost,tgtPort):nmScan = nmap.PortScanner()nmScan.scan(tgtHost,tgtPort)state=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']print "[*] " + tgtHost + " tcp/"+tgtPort +" "+statedef 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.tgtHosttgtPorts = str(options.tgtPort).split(',')if (tgtHost == None) | (tgtPorts[0] == None):print parser.usageexit(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 mainnmapScan(tgtHost, tgtPort)File "nmapScan.py", line 7, in nmapScanstate=nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
ValueError: invalid literal for int() with base 10: '20-25'
Answer

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 listports = spec.split(',')elif '-' in spec:# Port rangestart, end = map(int, spec.split('-'))ports = range(start, end + 1)else:# Single portports = [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.

https://en.xdnf.cn/q/118635.html

Related Q&A

Implementing a Python algorithm for solving the n-queens problem efficiently

I am working on a project that requires me to solve the n-queens problem efficiently using Python. I have already implemented a basic recursive algorithm to generate all possible solutions, but I am lo…

Annotations with pointplot

I am using a pointplot in seaborn.import seaborn as sns sns.set_style("darkgrid") tips = sns.load_dataset("tips") ax = sns.pointplot(x="time", y="total_bill", hu…

How do I get data in tuples and tuples in lists?

I am trying to figure out the route that a car takes in a fictional manhattan. I have defined the starting position, being(1,2)(in a 2 dimensional grid).manhattan=[[1, 2, 3, 4, 5],[6, 7, 8, 9, 10],[11…

How to return a value from a table or dataframe given 2 inputs? Python

Lets say this is my dataframe:and the user inputs B and 2Then the function would return clemintineIs there a way to do this without using a bunch of if elif statements. The actual dataframe Im working …

tkinter progressbar for multiprocessing

I have a program that encrypts files and I used multiprocessing to make it faster, but I am having trouble with the tkinter progress bar. I have implemented it but it completes immediately or lags in b…

How to add and subtract in python

So I am making a statcalc and everything is working except adding. When I select the option to add it just skips it and says select an option. I was wondering whats wrong with it?numberstoadd = input(…

Python: deferToThread XMLRPC Server - Twisted - Cherrypy?

This question is related to others I have asked on here, mainly regarding sorting huge sets of data in memory.Basically this is what I want / have:Twisted XMLRPC server running. This server keeps seve…

How do I make a linear gradient with Python Turtle?

Im currently trying to replicate this image: https://i.sstatic.net/fymWE.jpg Im trying to make that gradient in the background but I have zero clue how to do it and theres basically nothing on the inte…

Python - Converting an array to a list causes values to change

>>> import numpy as np >>> a=np.arange(0,2,0.2) >>> a array([ 0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8]) >>> a=a.tolist() >>> a [0.0, 0.2, …

Understand Python Function [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable…