Python KeyError扫描打开端口的主机列表

时间:2014-12-29 20:14:09

标签: python list nmap port-scanning

我的python脚本中有我的ip列表,我正在尝试对每个脚本运行nmap扫描以查找开放端口。我一直收到这个错误:

Traceback (most recent call last):
  File "rscan.py", line 33, in <module>
    main()
  File "rscan.py", line 30, in main
    vulnscan(nm, L)
  File "rscan.py", line 6, in vulnscan
    for port in nm[item].all_tcp():
  File "build/bdist.linux-x86_64/egg/nmap/nmap.py", line 567, in __getitem__
KeyError: u'IP ADDRESS HERE'

(但“IP ADDRESS HERE”部分中有一个实际的IP地址。)

我尝试过的代码扫描部分是:

for item in L:
        for port in nm[item].all_tcp():
            state= nm[item]['tcp'][port]['state']
            if state== 'open':
                print state

'L'是包含我的IP地址的列表。

使用nmap扫描开放端口的小型IP地址列表的正确方法是什么?

1 个答案:

答案 0 :(得分:0)

像这样,基于你的代码:

for item in L:
    if item in nm.all_hosts():
        for port in nm[item].all_tcp():
            state = nm[item]['tcp'][port]['state']
            if state == 'open':
                print state

检查指定的ip地址是否在nm.all_hosts()(返回ips列表),以便您以后安全地查询nm[item]

请注意,只需将L列表与nm.all_hosts()返回的ip地址列表相交即可使此代码更清晰:

items = list(set(L) & set(nm.all_hosts()))

for item in items:
    for port in nm[item].all_tcp():
        state = nm[item]['tcp'][port]['state']
        if state == 'open':
            print state