diff --git a/Python/geo_locate_ip.py b/Python/geo_locate_ip.py new file mode 100644 index 0000000..ef3dfb7 --- /dev/null +++ b/Python/geo_locate_ip.py @@ -0,0 +1,26 @@ +# Useful python code snippet for quickly geolocating an IP address + +import re +import sys +import urllib2 +import BeautifulSoup + +usage = "Run the script: ./geolocate.py " + +if len(sys.argv)!=2: + print(usage) + sys.exit(0) + +if len(sys.argv) > 1: + ipaddr = sys.argv[1] + +geody = "http://www.geody.com/geoip.php?ip=" + ipaddr +html_page = urllib2.urlopen(geody).read() +soup = BeautifulSoup.BeautifulSoup(html_page) + +# Filter paragraph containing geolocation info. +paragraph = soup('p')[3] + +# Remove html tags using regex. +geo_txt = re.sub(r'<.*?>', '', str(paragraph)) +print geo_txt[32:].strip()