skip to Main Content
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


  1. You can use json.dump() instead of json.dumps() to writes the file directly, try changing to this:

    with open('./test.json', "w") as jsonfile:
        json.dump(build_info_arr, jsonfile, indent=4, sort_keys=False)
    
    Login or Signup to reply.
  2. Not directly related to your question but a few things:

    1. Shodan already collects that information and stores it in the mongodb.buildInfo property: https://datapedia.shodan.io/property/mongodb.html
    2. You can use a search query of "product:mongodb" which is shorter and takes advantage of our fingerprinting so you can find services on non-standard ports.
    3. Use the Shodan.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
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search