Sunday, 2 September 2012

Reverse IP lookup using new Bing API

Bing has recently changed it's API and has moved it to datamarket.azure.com. It allows 5000 searches/month for free. The python script given below will find all the domains hosted at a user specified IP address.

A reverse lookup can be made using an IP address or a domain name. To run this script, you will require to register at the above mentioned website in order to get the account key.

import urllib2, socket,sys,base64
from xml.dom.minidom import parse, parseString


def showhelp():
        print """
#####################################################
#  Reverse Host python script by oldman lab0ratory  #
#             visit oldmanlab.blogspot.com          #
#####################################################
Usage: python revhost.py -key [ACCOUNT_KEY] [OPTIONS]

[OPTIONS]

-ip     [IP ADDRESS]
-domain [DOMAIN NAME]
"""

def bing(account_key,ip):
    sites = []
    skip = 0
    top = 50

    while skip < 200:
          url = "https://api.datamarket.azure.com/Data.ashx/Bing/Search/v1/Web?Query='ip:%s'&$top=%s&$skip=%s&$format=Atom"%
          (ip,top,skip)
          request = urllib2.Request(url)
          auth = base64.encodestring("%s:%s" % (account_key, account_key)).replace("\n", "")
          request.add_header("Authorization", "Basic %s" % auth)
          res = urllib2.urlopen(request)
          data = res.read()

          xmldoc = parseString(data)
          site_list = xmldoc.getElementsByTagName('d:Url')
          for site in site_list:
              domain = site.childNodes[0].nodeValue
              domain = domain.split("/")[2]
              if domain not in sites:
                 sites.append(domain)

          skip += 50

    print "Total domains found: %s \n\n" %(len(sites))
    for site in sites:
        print site


def options(arguments):
   try:
    count = 0
    ip = ""
    account_key = ""
    for arg in arguments:
        if arg == "-ip":
           ip = arguments[count+1]
        elif arg == "-domain":
           ip = socket.gethostbyname(arguments[count+1])
        elif arg == "-key":
           account_key = arguments[count+1]
        count = count+1
    bing(account_key,ip)
   except:
    print "something went wrong"

if __name__ == "__main__":
   if len(sys.argv) <= 3 or "-key" not in sys.argv:
      showhelp()
      sys.exit()
   else:
      options(sys.argv)

You can download the script from here