“KeyError:'(插入IP)'”是什么意思?

时间:2015-03-18 22:03:44

标签: python linux ubuntu

我正在使用Violent Python书籍,并且有一个错误阻止我超越第一个nmap版本(第40-41页)。在VM上使用Ubuntu 14.04。我正在输入' python nmapScan.py -H 10.50.60.125 -p 21,1720'进入终端。

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('usage %prog '+\
                                   '-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()

这是错误:

File "nmapScan.py", line 24, in <module>
    main()
File "nmapScan.py", line 21, in main
    nmapScan(tgtHost, tgtPort)
File "nmapScan.py", line 7, in nmapScan
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
File "build/bdist.linux-x86_64/egg/nmap/nmap.py", line 567, in __getitem__
KeyError:'10.50.60.125'

3 个答案:

答案 0 :(得分:1)

无法访问此主机10.50.60.125

ping 10.50.60.125
PING 10.50.60.125 (10.50.60.125): 56 data bytes
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1

尝试使用某些可访问的主机:127.0.0.1

答案 1 :(得分:1)

nmap中的KeyError表示ip无法访问。您应该验证IP实际上已经启动。

如果您不确定主持人是否已启用,则需要try/except

try:
    state = nmScan[tgtHost]['tcp'][int(tgtPort)]['state']
except KeyError as e:
   print(e)
   return

答案 2 :(得分:0)

这是因为nmap没有扫描端口信息, 你可以查看

nmScan = nmap.PortScanner()
data = nmScan.scan(tgtHost,tgtPort)
print(data.get(tgtHost))

你会发现输出值是空的

来自源鳕鱼,我们可以知道: nmScan[tgtHost]等于data.get(tgtHost)[tgtHost]

更好的方法是使用data.get(tgtHost)[tgtHost]data.get(tgtHost).get(tgtHost, {})

获取信息