How to use the maxminddb.errors function in maxminddb

To help you get started, we’ve selected a few maxminddb examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github constverum / ProxyBroker / proxybroker / resolver.py View on Github external
def get_ip_info(ip):
        """Return geo information about IP address.

        `code` - ISO country code
        `name` - Full name of country
        `region_code` - ISO region code
        `region_name` - Full name of region
        `city_name` - Full name of city
        """
        # from pprint import pprint
        try:
            ipInfo = _mmdb_reader.get(ip) or {}
        except (maxminddb.errors.InvalidDatabaseError, ValueError):
            ipInfo = {}

        code, name = '--', 'Unknown'
        city_name, region_code, region_name = ('Unknown',) * 3
        if 'country' in ipInfo:
            code = ipInfo['country']['iso_code']
            name = ipInfo['country']['names']['en']
        elif 'continent' in ipInfo:
            code = ipInfo['continent']['code']
            name = ipInfo['continent']['names']['en']
        if 'city' in ipInfo:
            city_name = ipInfo['city']['names']['en']
        if 'subdivisions' in ipInfo:
            region_code = ipInfo['subdivisions'][0]['iso_code']
            region_name = ipInfo['subdivisions'][0]['names']['en']
        return GeoData(code, name, region_code, region_name, city_name)
github m-lab / mlab-ns / server / mlabns / util / maxmind.py View on Github external
def get_geo_reader():
    global _maxmind_geo_reader
    if _maxmind_geo_reader is None:
        try:
            # The third parameter is for the "mode", which corresponds to
            # various integer constants in the MaxMind code. 16 corresponds to
            # MODE_FD, which means that we will be passing a file descriptor,
            # not a path to the MM database.
            maxmind_database_file = get_database_file()
            geo_reader = geoip2.database.Reader(maxmind_database_file, None, 16)
        except maxminddb.errors.InvalidDatabaseError:
            logging.error('Invalid MaxMind database file.')
            return GeoRecord()
        except IOError:
            logging.error('Cannot read MaxMind database file.')
            return GeoRecord()

        _maxmind_geo_reader = geo_reader

    return _maxmind_geo_reader
github Antergos / Cnchi / src / geoip.py View on Github external
def _load_database(self, db_path, myip):
        """ Loads cities database """
        try:
            reader = geoip2.database.Reader(db_path)
            self.record = reader.city(myip)
        except maxminddb.errors.InvalidDatabaseError as err:
            logging.error(err)
github jpsenior / threataggregator / threataggregator.py View on Github external
latitude = response.location.latitude
                else:
                    latitude = 0
            if not longitude:
                if response.location.longitude:
                    longitude = response.location.longitude
                else:
                    longitude = 0
            # Close the GeoDB reader
            reader.close()

        # Not all IP addresses will be in the Maxmind database
        except geoip2.errors.AddressNotFoundError:
            pass

        except maxminddb.errors.InvalidDatabaseError as e:
            raise "Invalid GeoIP database %s" % e

        # Signed degrees format for latitude and longitude
        # Represented DDD.ddd with maximum 8 decimal places.
        # Longitudes range from -90 to 90
        # Latitudes range from -180 to 180
        if latitude < -90.0 or latitude > 90.0:
            latitude = 0
        if longitude < -180.0 or longitude > 180.0:
            longitude = 0
        # Translate CIDR to a list of IP addresses for Arcsight
        for i in netaddr.IPNetwork(ip):
            self.entries.append(
                {'ip': i, 'source': source, 'description': description, 'priority': priority,
                 'reputation': reputation, 'latitude': latitude, 'longitude': longitude, 'city': city,
                 'country': country})
github securestate / king-phisher / king_phisher / geoip.py View on Github external
:param str database_file: The GeoLite2 database file to use.
	:return: The initialized GeoLite2 database object.
	:rtype: :py:class:`geoip2.database.Reader`
	"""
	# pylint: disable=global-statement
	global _geoip_db
	if not os.path.isfile(database_file):
		db_path = find.data_file('GeoLite2-City.mmdb')
		if db_path is None:
			raise errors.KingPhisherResourceError('the default geoip database file is unavailable')
		logger.info('initializing the default geoip database')
		shutil.copyfile(db_path, database_file)
	try:
		_geoip_db = geoip2.database.Reader(database_file)
	except maxminddb.errors.InvalidDatabaseError:
		logger.warning('the geoip database file is invalid, downloading a new one')
		download_geolite2_city_db(database_file)
		_geoip_db = geoip2.database.Reader(database_file)
	metadata = _geoip_db.metadata()
	if not metadata.database_type == 'GeoLite2-City':
		raise ValueError('the connected database is not a GeoLite2-City database')
	build_date = datetime.datetime.fromtimestamp(metadata.build_epoch)
	if build_date < datetime.datetime.utcnow() - datetime.timedelta(days=90):
		logger.warning('the geoip database is older than 90 days')
	return _geoip_db
github jpsenior / threataggregator / threataggregator.py View on Github external
from http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz

    :return: geoip2.database.Reader object
    """

    # Pull everything off the internet if it isn't cached
    geofilename = 'cache/GeoLite2-City.mmdb'
    url = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-City.mmdb.gz'
    gzipfile = 'cache/GeoLite2-City.mmdb.gz'

    if os.path.isfile(geofilename):
        try:
            reader = geoip2.database.Reader(geofilename)
        except ValueError as e:
            raise Exception("Error accessing GeoLite database: %s" % e)
        except maxminddb.errors.InvalidDatabaseError as e:
            raise Exception("Invalid DB error %s - %s " % (geofilename, e))
        return reader
    else:

        try:
            print("Maxmind database not cached. Attempting to pull from {0}".format(url))
            download_file(url, gzipfile)
        except requests.ConnectionError:
            e = sys.exc_info()[0]
            print('Connection interrupted while downloading Maxmind Database: {0} - {1}'.format(url, e))
        except IOError:
            e = sys.exc_info()[0]
            print('Error downloading Maxmind Database: %s - %s'.format(url, e))

        # Open Gzip
        f = gzip.open(gzipfile, 'rb')