Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pronto
Created March 25, 2015 15:32
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pronto/28040f7ea465c1a72de4 to your computer and use it in GitHub Desktop.
Save pronto/28040f7ea465c1a72de4 to your computer and use it in GitHub Desktop.
geo.py
#!/usr/bin/env python2.7
import sys,re
import geoip2.database
def extractIPs(fileContent):
pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})"
ips = [each[0] for each in re.findall(pattern, fileContent)]
for item in ips:
location = ips.index(item)
ip = re.sub("[ ()\[\]]", "", item)
ip = re.sub("dot", ".", ip)
ips.remove(item)
ips.insert(location, ip)
return ips
#assumes /usr/share/GeoIP for ip geo ip
#http://dev.maxmind.com/geoip/geoip2/geolite2/
geo_look = geoip2.database.Reader('/usr/share/GeoIP/GeoLite2-Country.mmdb')
if __name__ == "__main__":
for line in sys.stdin:
#sys.stderr.write("DEBUG: got line: " + line)
#sys.stdout.write(line)
#get all the IP's on that line
ips_line = extractIPs(line)
for ip in ips_line:
try:
country=geo_look.country(ip).country.name
except ValueError:
country='value error'
except:
country='other error'
sys.stdout.write(ip + " is " + country+"\n")
#print country
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment