Last active
August 29, 2015 14:05
-
-
Save pronto/740ab5c22fa2bd7fd921 to your computer and use it in GitHub Desktop.
pipe things to it; because why not
This file contains hidden or 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
% cat test.txt | ./geo.py | |
171.111.153.168 is China | |
4.2.2.2 is United States | |
91.188.124.232 is Poland | |
8.6.6.4 is United States | |
66.163.128.206 is United States | |
62.210.38.226 is France | |
94.173.21.140 is United Kingdom | |
117.21.191.208 is China |
This file contains hidden or 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 python2.7 | |
import sys,re | |
import geoip2.database | |
#extractIPs is from http://stackoverflow.com/questions/17327912/python-parse-ipv4-addresses-from-string-even-when-censored | |
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 |
This file contains hidden or 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
7 171.111.153.168 4.2.2.2 | |
3 91.188.124.232 8.6.6.4 | |
3 66.163.128.206 | |
3 62.210.38.226 | |
2 94.173.21.140 | |
2 117.21.191.208 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment