-
Notifications
You must be signed in to change notification settings - Fork 15
/
csv_to_mmdb.py
36 lines (26 loc) · 866 Bytes
/
csv_to_mmdb.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import csv
from collections import defaultdict
from netaddr import IPNetwork, IPSet
from mmdb_writer import MMDBWriter
def main():
writer = MMDBWriter(
4, "Test.GeoIP", languages=["EN"], description="Test IP library"
)
data = defaultdict(list)
# merge cidr
with open("fake_ip_info.csv") as f:
reader = csv.DictReader(f)
for line in reader:
data[(line["country"], line["isp"])].append(
IPNetwork(f'{line["ip"]}/{line["prefixlen"]}')
)
for index, cidrs in data.items():
writer.insert_network(IPSet(cidrs), {"country": index[0], "isp": index[1]})
writer.to_db_file("fake_ip_library.mmdb")
def test_read():
import maxminddb
m = maxminddb.open_database("fake_ip_library.mmdb")
r = m.get("3.1.1.1")
print(r)
if __name__ == "__main__":
main()