为什么我的代码不写它从build_info函数接收到json文件的数据?


api = shodan.Shodan(api_key)
query = 'MongoDB Server Information n{ "process": "mongod" port:27017'
build_info_arr = []
try:
results = api.search(query)
print('Total Results: %sn' % results['total'])
for result in results['matches']:
if "Authentication partially enabled" not in result['data']:
print('IP: {}'.format(result['ip_str']))
ip: str = format(result['ip_str'])
collections = mongodb_search.build_info(ip)
if collections:
data = json.loads(collections)
for build_infos in data.items():
build_info_arr.append(build_infos)
except shodan.APIError as e:
print('Error: {}'.format(e))
with open('./test.json', "wt") as jsonfile:
jsonfile.write(json.dumps(build_info_arr, indent=4, sort_keys=False))

我的build_info函数在这里:

def build_info(ip):
try:
client = pymongo.MongoClient(ip, 27017, maxPoolSize=10)
data = ''
for build_info in client.db.command({'buildInfo': 1}):
data += str(json.dumps(build_info))
file = json.loads(data)
return file
except:
print('Error: Cannot retrieve buildinfo.')

您可以使用json.dump()而不是json.dumps()直接写入文件,尝试更改为:

with open('./test.json', "w") as jsonfile:
json.dump(build_info_arr, jsonfile, indent=4, sort_keys=False)

与你的问题没有直接关系,但有一些事情:

  1. Shodan已经收集了这些信息并将其存储在mongodb.buildInfo属性中:https://datapedia.shodan.io/property/mongodb.html
  2. 您可以使用"product:mongodb"它更短,并利用我们的指纹识别,所以你可以找到非标准端口的服务。
  3. 使用Shodan.search_cursor(query)方法迭代结果。它处理分页。参见:https://help.shodan.io/guides/how-to-download-data-with-api

最新更新