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))
My build_info function is here:
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.')
2
Answers
You can use
json.dump()
instead ofjson.dumps()
to writes the file directly, try changing to this:Not directly related to your question but a few things:
mongodb.buildInfo
property: https://datapedia.shodan.io/property/mongodb.htmlShodan.search_cursor(query)
method to iterate over results. It handles paging for you. See: https://help.shodan.io/guides/how-to-download-data-with-api