geoipy: A simple IP geolocation python script.


/ Published in: Python
Save to your folder(s)



Copy this code and paste it in your HTML
  1. #!/usr/bin/env python
  2. """
  3. geoipy.py
  4. A simple IP geolocation python script.
  5. Uses geody.com geolocation web service.
  6. Requires BeautifulSoup library.
  7.  
  8. Example:
  9. $ ./geoipy.py 198.117.0.122
  10. IP: 198.117.0.122 Location: MSFC, ALABAMA, \
  11. United States (National Aeronautics and Space Administration)
  12.  
  13. ksaver, June 18, 2011.
  14. Public Domain Code.
  15. """
  16.  
  17. import re
  18. import sys
  19. from urllib import urlopen
  20. from BeautifulSoup import BeautifulSoup as Soup
  21.  
  22. def main(ipaddr):
  23. """Geo-locates an IP address passed in argv[1]."""
  24.  
  25. geody = "http://www.geody.com/geoip.php?ip=" + ipaddr
  26. html_page = urlopen(geody).read()
  27. soup = Soup(html_page)
  28.  
  29. # Filter paragraph containing geolocation info.
  30. paragraph = soup('p')[3]
  31.  
  32. # Remove html tags using regex.
  33. geo_txt = re.sub(r'<.*?>', '', str(paragraph))
  34. print geo_txt[32:].strip() + '\n'
  35.  
  36. if __name__ == "__main__":
  37. if len(sys.argv) > 1:
  38. main(sys.argv[1])
  39. else:
  40. main('127.0.0.1')

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.