Created
March 16, 2016 00:52
-
-
Save vandot/0f4e9fceb7665f83c9da to your computer and use it in GitHub Desktop.
Fetch geoip data and create Bind9 ACL based on continents for poor man's GSLB service
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
#!/usr/bin/env python | |
import csv | |
import urllib | |
import zipfile | |
import os | |
link = 'http://geolite.maxmind.com/download/geoip/database/GeoLite2-Country-CSV.zip' | |
csv1 = 'GeoLite2-Country-Blocks-IPv4.csv' | |
csv2 = 'GeoLite2-Country-Locations-en.csv' | |
output = 'BindACL.conf' | |
downzip = 'geolite.zip' | |
downfile = urllib.URLopener() | |
downfile.retrieve(link, downzip) | |
zfile = zipfile.ZipFile(downzip) | |
filelist = zfile.namelist() | |
for f in filelist: | |
fsplit = f.split('/') | |
if fsplit[1] == csv1: | |
file1 = f | |
elif fsplit[1] == csv2: | |
folder = fsplit[0] | |
file2 = f | |
zfile.extract(file1) | |
zfile.extract(file2) | |
dict = {} | |
dict2 = {} | |
final = {} | |
with open(file1) as csvfile: | |
reader = csv.DictReader(csvfile) | |
for row in reader: | |
dict[row['network']] = row['geoname_id'] | |
with open(file2) as csvfile2: | |
reader = csv.DictReader(csvfile2) | |
for row in reader: | |
dict2[row['geoname_id']] = row['continent_code'] | |
# Brute force :D | |
for code2, country in dict2.iteritems(): | |
final[country] = final.get(country, []) | |
for ip, code in dict.iteritems(): | |
if code == code2: | |
final[country].append(ip) | |
f = open(output,'w') | |
for country in final.keys(): | |
f.write('acl "%s" {\n' % country) | |
for ip in final[country]: | |
f.write(' %s;\n' % ip) | |
f.write('};\n') | |
f.close() | |
# Cleanup | |
os.remove(downzip) | |
os.remove(file1) | |
os.remove(file2) | |
os.rmdir(folder) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment