使用nmap&输入端口的范围光学分析仪 [英] Inputting range of ports with nmap & optparser
问题描述
这是脚本
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()
当我尝试在命令行中输入一系列端口时,出现此错误.有人可以帮我吗?我是python的新手.在此先感谢!
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'
推荐答案
您需要区分这两种不同的格式,如果使用了m-n
范围格式,请在-"处分割以获取边界,然后创建使用range()
列出端口,并将tgtPorts
设置为该范围.
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)
代替当前的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)
但是请注意,这仍然不支持完整的 nmap端口范围规范语法.您只能使用逗号分隔的列表,或者使用m-n
定义的范围,但不能同时使用两者.
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.
请参阅 range()
和 map()
了解有关这些功能如何工作的详细信息.
See the documentation for range()
and map()
for details on how those functions work.
这篇关于使用nmap&输入端口的范围光学分析仪的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!