搜索Shodan API时的错误处理

0 投票
1 回答
976 浏览
提问于 2025-04-17 18:17

我正在尝试写一个Python脚本,这个脚本会搜索Shodan API,并返回ID、CVE和描述。不过,有些搜索结果(比如“java”)没有对应的CVE(或者CVE键),这导致我的脚本出错。我知道我需要用try/except来处理错误,但我在网上找资料时没有找到合适的解决办法。下面是我遇到的错误信息,下面是我的代码。非常感谢!

--------错误-------

    print '%s: %s: %s' % (exploit['id'], exploit['cve'], exploit['description'])
KeyError: 'cve

--------我的代码------

from shodan import WebAPI
api = WebAPI("my shodan key")

user_selection = raw_input("Enter something: ")
print "searching for", (user_selection),"....."

results = api.exploitdb.search(user_selection)

for exploit in results['matches']:
    print '%s: %s: %s' % (exploit['id'], exploit['cve'], exploit['description'])

1 个回答

0

看起来你想用 dict.get 这个方法,并且想给它设置一个默认值,这样当你查找的键不存在时,就会返回这个默认值:

print '%s: %s: %s' % (exploit.get('id', '[blank]'), exploit.get('cve', '[blank]'), exploit.get('description', '[blank]'))

撰写回答