Advertisement
The_Defalt

maxmind_db_ip_geolocator.py

May 7th, 2016
3,755
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.18 KB | None | 0 0
  1. #! /usr/bin/python
  2.  
  3. #Hello fellow hackers! My name is Defalt
  4. #I built a very basic version of this tool a long time ago and recently did a re-write
  5. #The first re-write had some awkward usage of the argparse module, so this update is going to fix it
  6. #Original version: http://pastebin.com/J5NLnThL
  7. #This will query the MaxMind database to get an approximate geolocation of an IP address
  8. #Happy hacking! -Defalt
  9.  
  10. import sys
  11. import socket
  12. import urllib
  13. import gzip
  14. import os
  15. try:
  16.     import pygeoip
  17. except ImportError:
  18.     print '[!] Failed to Import pygeoip'
  19.     try:
  20.         choice = raw_input('[*] Attempt to Auto-install pygeoip? [y/N] ')
  21.     except KeyboardInterrupt:
  22.         print '\n[!] User Interrupted Choice'
  23.         sys.exit(1)
  24.     if choice.strip().lower()[0] == 'y':
  25.         print '[*] Attempting to Install pygeoip... ',
  26.         sys.stdout.flush()
  27.         try:
  28.             import pip
  29.             pip.main(['install', '-q', 'pygeoip'])
  30.             import pygeoip
  31.             print '[DONE]'
  32.         except Exception:
  33.             print '[FAIL]'
  34.             sys.exit(1)
  35.     elif choice.strip().lower()[0] == 'n':
  36.         print '[*] User Denied Auto-install'
  37.         sys.exit(1)
  38.     else:
  39.         print '[!] Invalid Decision'
  40.         sys.exit(1)
  41.  
  42. class Locator(object):
  43.     def __init__(self, url=False, ip=False, datfile=False):
  44.         self.url = url
  45.         self.ip = ip
  46.         self.datfile = datfile
  47.         self.target = ''
  48.     def check_database(self):
  49.         if not self.datfile:
  50.             self.datfile = '/usr/share/GeoIP/GeoLiteCity.dat'
  51.         else:
  52.             if not os.path.isfile(self.datfile):
  53.                 print '[!] Failed to Detect Specified Database'
  54.                 sys.exit(1)
  55.             else:
  56.                 return
  57.         if not os.path.isfile(self.datfile):
  58.             print '[!] Default Database Detection Failed'
  59.             try:
  60.                 choice = raw_input('[*] Attempt to Auto-install Database? [y/N] ')
  61.             except KeyboardInterrupt:
  62.                 print '\n[!] User Interrupted Choice'
  63.                 sys.exit(1)
  64.             if choice.strip().lower()[0] == 'y':
  65.                 print '[*] Attempting to Auto-install Database... ',
  66.                 sys.stdout.flush()
  67.                 if not os.path.isdir('/usr/share/GeoIP'):
  68.                     os.makedirs('/usr/share/GeoIP')
  69.                 try:
  70.                     urllib.urlretrieve('http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz', '/usr/share/GeoIP/GeoLiteCity.dat.gz')
  71.                 except Exception:
  72.                     print '[FAIL]'
  73.                     print '[!] Failed to Download Database'
  74.                     sys.exit(1)
  75.                 try:
  76.                     with gzip.open('/usr/share/GeoIP/GeoLiteCity.dat.gz', 'rb') as compressed_dat:
  77.                         with open('/usr/share/GeoIP/GeoLiteCity.dat', 'wb') as new_dat:
  78.                             new_dat.write(compressed_dat.read())
  79.                 except IOError:
  80.                     print '[FAIL]'
  81.                     print '[!] Failed to Decompress Database'
  82.                     sys.exit(1)
  83.                 os.remove('/usr/share/GeoIP/GeoLiteCity.dat.gz')
  84.                 print '[DONE]\n'
  85.             elif choice.strip().lower()[0] == 'n':
  86.                 print '[!] User Denied Auto-Install'
  87.                 sys.exit(1)
  88.             else:
  89.                 print '[!] Invalid Choice'
  90.                 sys.exit(1)
  91.     def query(self):
  92.         if not not self.url:
  93.             print '[*] Translating %s: ' %(self.url),
  94.             sys.stdout.flush()
  95.             try:
  96.                 self.target += socket.gethostbyname(self.url)
  97.                 print self.target
  98.             except Exception:
  99.                 print '\n[!] Failed to Resolve URL'
  100.                 return
  101.         else:
  102.             self.target += self.ip
  103.         try:
  104.             print '[*] Querying for Records of %s...\n' %(self.target)
  105.             query_obj = pygeoip.GeoIP(self.datfile)
  106.             for key, val in query_obj.record_by_addr(self.target).items():
  107.                 print '%s: %s' %(key, val)
  108.             print '\n[*] Query Complete!'
  109.         except Exception:
  110.             print '\n[!] Failed to Retrieve Records'
  111.             return
  112.  
  113. if __name__ == '__main__':
  114.     import argparse
  115.     parser = argparse.ArgumentParser(description='IP Geolocation Tool')
  116.     parser.add_argument('--url', help='Locate an IP based on a URL', action='store', default=False, dest='url')
  117.         parser.add_argument('-t', '--target', help='Locate the specified IP', action='store', default=False, dest='ip')
  118.         parser.add_argument('--dat', help='Custom database filepath', action='store', default=False, dest='datfile')
  119.     args = parser.parse_args()
  120.     if ((not not args.url) and (not not args.ip)) or ((not args.url) and (not args.ip)):
  121.         parser.error('invalid target specification')
  122.     try:
  123.         locate = Locator(url=args.url, ip=args.ip, datfile=args.datfile)
  124.         locate.check_database()
  125.         locate.query()
  126.     except Exception:
  127.         print '\n[!] An Unknown Error Occured'
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement