Last active
April 2, 2020 22:22
-
-
Save ahmetkotan/0b3d0492e70dba052e5eb9471cb7861c to your computer and use it in GitHub Desktop.
MMDB Geo Location DB to CSV
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
import os | |
import sys | |
import re | |
import geoip2.database | |
from geoip2.errors import AddressNotFoundError | |
# pip install geoip2 | |
# python3 mmdb_to_csv.py -d geoip.mmdb -i ip_list.csv -o ip_locations.csv | |
parser = argparse.ArgumentParser() | |
parser.add_argument("--database", "-d", type=str, help="MMDB Database", required=True) | |
parser.add_argument("--input", "-i", type=str, help="IP List CSV", required=True) | |
parser.add_argument("--output", "-o", type=str, help="Output CSV", required=True) | |
args = parser.parse_args() | |
if not os.path.isfile(args.input): | |
print() | |
print("Input File does not exists.") | |
print() | |
sys.exit(1) | |
if not os.path.isfile(args.database): | |
print() | |
print("Database File does not exists.") | |
print() | |
sys.exit(1) | |
with open(args.input) as f: | |
ip_list = f.readlines() | |
ip_pattern = re.compile(r"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$") | |
geo_reader = geoip2.database.Reader(args.database) | |
with open(args.output, "w") as f: | |
f.write("SourceAddress,Country,City\n") | |
for line in ip_list: | |
line = line.strip() | |
if "," in line: | |
ip_addr = line.split(",")[0] | |
else: | |
ip_addr = line | |
if not ip_pattern.match(ip_addr): | |
continue | |
try: | |
ip_info = geo_reader.city(ip_addr) | |
city = ip_info.city.names.get("en", None) | |
if not city: | |
subdivisions = ip_info.subdivisions | |
if subdivisions: | |
city = subdivisions[0].names.get("en", "") | |
else: | |
city = "" | |
country = ip_info.country.names.get("en", "") | |
except AddressNotFoundError: | |
country = "" | |
city = "" | |
f.write("{0},{1},{2}\n".format(ip_addr, country, city)) | |
# print(ip_addr, country, city) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment