gpt4 book ai didi

python - "KeyError: '(插入 IP )'"是什么意思?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:16:48 31 4
gpt4 key购买 nike

我正在使用 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'

最佳答案

nmap 中的 KeyError 表示 ip 无法访问。您应该验证 ip 是否确实可用。

如果您不确定主机是否启动,您需要一个try/except:

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

关于python - "KeyError: '(插入 IP )'"是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29133574/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com