Created
February 5, 2012 19:06
-
-
Save laginha/1747286 to your computer and use it in GitHub Desktop.
Lookup IP addresses and get geolocation using GeoIP City Demo
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
from requests import post | |
import re, json, optparse | |
class GeoIpCity: | |
@staticmethod | |
def request( ip ): | |
response = post( "http://www.maxmind.com/app/lookup_city", {'ips': ip} ) | |
return ''.join( [i.strip() for i in response.content.split('\n')] ) | |
@staticmethod | |
def to_json( html ): | |
table = lambda x: re.findall( r'<table><tr>(.+)</tr></table><p>', x )[0] | |
keys = lambda x: [i for i in re.findall( r'>([a-zA-Z0-9\. ]*)</', x ) if i] | |
values = lambda x: re.findall( r'>([a-zA-Z0-9\.\- ]*)</font></td>', x ) | |
k, v = table( html ).split( r'</tr><tr>' ) | |
return dict( zip( keys(k), values(v) ) ) | |
if __name__ == '__main__': | |
parser = optparse.OptionParser() | |
parser.add_option('--ip', action='store', help='IP address you wish to lookup') | |
opts, sources = parser.parse_args() | |
if opts.ip: | |
html = GeoIpCity.request( opts.ip ) | |
dict_ = GeoIpCity.to_json( html ) | |
print json.dumps( dict_, indent=2 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment