Python whois.whois() Examples

The following are 30 code examples of whois.whois(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module whois , or try the search function .
Example #1
Source File: tulpar.py    From tulpar with GNU General Public License v3.0 8 votes vote down vote up
def whoisSorgu(url,dosyaAdi):
    query = whois.whois(url)
    print "[+]Domain: ", query.domain
    print "[+]Update time: ", query.get('updated_date')
    print "[+]Expiration time: ", query.get('expiration_date')
    print "[+]Name server: ", query.get('name_servers')
    print "[+]Email: ", query.get('emails')
    rapor = open(dosyaAdi, "a")
    raporIcerik=""
    raporIcerik+="[+]Domain: "+query.domain+"\n"
    raporIcerik+="[+]Update time: "+str(query.get('updated_date'))+"\n"
    raporIcerik+="[+]Expiration time: "+str(query.get('expiration_date'))+"\n"
    raporIcerik+="[+]Name server: "+str(query.get('name_servers'))+"\n"
    raporIcerik+="[+]Email: "+str(query.get('emails'))+"\n"
    rapor.write(raporIcerik)
    rapor.close() 
Example #2
Source File: PhishingKitHunter.py    From PhishingKitHunter with GNU Affero General Public License v3.0 7 votes vote down vote up
def LogPattern_search(Line):
    global ResTimestamp
    global ResRequestEx
    global ResRefererEx
    try:
        # Group is [0]: timestamp, [1]: file request, [2]: referer
        ResRegEx = CompRegEx.match(Line).group(1, 2, 3)
        ResTimestamp = ResRegEx[0]
        ResRequestEx = ResRegEx[1]
        if ResRegEx[2] is not '-':
            ResRefererEx = ResRegEx[2]

    except:
        # Except direct connexion
        pass


# Domain extraction (for whois)
# TODO: find a way for whois request behind a HTTP proxy 
Example #3
Source File: who.py    From netpwn with GNU General Public License v3.0 6 votes vote down vote up
def whois_lookup():
    """Perform whois."""
    try:
        print colored('Enter a URL to get whois data', 'green')
        domain = raw_input(colored('(netpwn: whois) > ', 'red'))
        target = [domain]
        targets = whois(target[0])
        print colored('name: ' + targets['name'], 'green')
        print colored('city: ' + targets['city'], 'green')
        print colored('zipcode: ' + targets['zipcode'], 'green')
        print colored('country: ' + targets['country'], 'green')
        print colored('state: ' + targets['state'], 'green')
        print colored('registrar: ' + targets['registrar'], 'green')
        print colored('address : ' + targets['address'], 'green')
        print colored('org : ' + targets['org'], 'green')

        for domains in targets['domain_name']:
            print colored('DNS: ' + domains, 'green')

        for emails in targets['emails']:
            print colored('emails : ' + emails, 'green')

    except TypeError:
        print colored('Cannot retrieve information', 'red') 
Example #4
Source File: whois_search.py    From punter with The Unlicense 6 votes vote down vote up
def whois_ip(ip):

    # Default to not found
    cidr, ranges = "CIDR not found", "Range not found"

    # Get whois for IP. Returns a list with dictionary
    ip_dict = IPWhois(ip).lookup_rws()

    if ip_dict['nets'][0].get('cidr'):
        cidr = ip_dict['nets'][0].get('cidr')

    if ip_dict['nets'][0].get('range'):
        ranges = ip_dict['nets'][0].get('range')

    sleep(2)

    return cidr, ranges 
Example #5
Source File: whois_check.py    From TR-PhishingList with MIT License 6 votes vote down vote up
def check_whois():
    for line in open(sys.argv[1], "r", encoding="utf8"):
        if line[0]== '#':
            pass
        else:
            try:
                w = whois.whois(line[:-1])
                print("""
                =============== Domain: {} ==============
                NameServer: {} \n 
                Name: {} \n
                Organization: {} \n
                Register Date: {} \n
                Expiration Date: {} \n
                =========================================""".format(line[:-1], w.name_servers, w.name, w.org , w.creation_date, w.expiration_date))
            except:
                print("WHOIS NOT FOUND: {}".format(line[:-1])) 
Example #6
Source File: whois.py    From ODIN with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self):
        """Everything that should be initiated with a new object goes here."""
        try:
            self.whoxy_api_key = helpers.config_section_map("WhoXY")["api_key"]
            try:
                balance_endpoint = self.whoxy_balance_uri.format(self.whoxy_api_key)
                balance_json = requests.get(balance_endpoint,timeout=self.requests_timeout).json()
                live_whois_balance = balance_json['live_whois_balance']
                reverse_whois_balance = balance_json['reverse_whois_balance']
                if live_whois_balance < 50:
                    click.secho("[*] You are low on WhoXY whois credits: {} credits".format(live_whois_balance),fg="yellow")
                if reverse_whois_balance < 50:
                    click.secho("[*] You are low on WhoXY reverse whois credits: {} credits".format(reverse_whois_balance),fg="yellow")
            except requests.exceptions.Timeout:
                click.secho("\n[!] The connection to WhoXY timed out!",fg="red")
            except requests.exceptions.TooManyRedirects:
                click.secho("\n[!] The connection to WhoXY encountered too many redirects!",fg="red")
            except requests.exceptions.RequestException as error:
                click.secho("\n[!] The connection to WhoXY encountered an error!",fg="red")
                click.secho("L.. Details: {}".format(error),fg="red")
        except Exception:
            self.whoxy_api_key = None
            click.secho("[!] Did not find a WhoXY API key.",fg="yellow") 
Example #7
Source File: run.py    From doxbox with MIT License 6 votes vote down vote up
def dns():
    description = """
    Targets, whether it be a company or a person, may utilize domains in order to
    display web content. Domains, especially those that are not properly configured,
    give penetration testers great opportunity to gather sensitive information in the
    form of metadata, whether it be an address from a WHOIS lookup, or nameservers."""

    form = forms.DNSForm()

    if flask.request.method == "POST":
        whois_data = whois.whois(flask.request.form["url"])

        # Subdomain enumeration using crt.sh
        _subdomain = subdomain_search(flask.request.form["url"])
        subdomain = [y['domain'] for y in to_dict_from_json(_subdomain)]
        # Re-render with appopriate parameters
        return flask.render_template('dns.html', title="DNS Enumeration Module",
                            user=user, description=description,
                            form=form, whois=whois_data, subdomain=subdomain)
    else:
        return flask.render_template('dns.html', title="DNS Enumeration Module",
                            user=user,description=description,
                            form=form, whois=None, subdomain=None)

# register filters 
Example #8
Source File: whois.py    From ODIN with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run_whois(self,domain):
        """Perform a WHOIS lookup for the provided target domain. The WHOIS results are returned
        as a dictionary.

        This can fail, usually if the domain is protected by a WHOIS privacy service or the
        registrar has their own WHOIS service.

        Parameters:
        domain      The domain to use for the WHOIS query
        """
        try:
            who = whois.whois(domain)
            results = {}
            # Check if info was returned before proceeding because sometimes records are protected
            if who.registrar:
                results['domain_name'] = who.domain_name
                results['registrar'] = who.registrar
                results['expiration_date'] = who.expiration_date
                results['registrant'] = who.name
                results['org'] = who.org
                results['admin_email'] = who.emails[0]
                results['tech_email'] = who.emails[1]
                results['address'] = "{}, {}{}, {}, {}".format(who.address,who.city,who.zipcode,who.state,who.country)
                results['dnssec'] = who.dnssec
            else:
                click.secho("[*] WHOIS record for {} came back empty. You might try looking at dnsstuff.com.".format(domain),fg="yellow")
            return results
        except Exception as error:
            click.secho("[!] The WHOIS lookup for {} failed!".format(domain),fg="red")
            click.secho("L.. Details: {}".format(error),fg="red") 
Example #9
Source File: suneo-whois-libreborme.py    From Shodita with GNU General Public License v3.0 5 votes vote down vote up
def check_domain_mongodb(dominio):
	global client, db
	if db.Shodita.find({"dominio": dominio, "bot": "Suneo-whois-libreborme"}).count() >= 1:
		return True
	else:
		return False 
Example #10
Source File: suneo-whois-libreborme.py    From Shodita with GNU General Public License v3.0 5 votes vote down vote up
def insert_mongodb(w, lb, dominio):
	try:
		client = MongoClient()
		db = client.test
		date_Insert = time.strftime("%H:%M:%S")
		date_Update = ""
		cursor = db.Shodita.insert({"dominio":dominio, "bot":"Suneo-whois-libreborme", "whois":w,"libreborme":lb,"date_insert": date_Insert, "date_Update": date_Update})
		print colores.azul + "[INFO] INSERT IN DB" + colores.normal
	except:
		print "[WARNING]ERROR INSERT MONGODB" 
Example #11
Source File: suneo-whois-libreborme.py    From Shodita with GNU General Public License v3.0 5 votes vote down vote up
def get_target():
	global client, db
	cursor = db.Shodita.find({"bot":"Suneo"})
	for document in cursor:
		if check_domain_mongodb(document["dominio"]):
			print colores.verde + "[INFO] Domain: " + document["dominio"] + " already scanned" + colores.normal
		else:
			print "|"
			print colores.HEADER + "[NEW TARGET][INFO] Domain: " + colores.normal +  document["dominio"] 
			w = whois.whois(document['dominio'])
			name = w.name
			print colores.verde + "|----[INFO] OWNER: " + colores.normal + name
			try:
				url = "https://libreborme.net/borme/api/v1/persona/search/?q=" + str(name.replace(" ", "%20"))
				html = urllib2.urlopen(url).read()
				data = json.loads(html)
				if data["objects"][0]["resource_uri"]:
					url = "https://libreborme.net" + data["objects"][0]["resource_uri"]
					html = urllib2.urlopen(url).read()
					data = json.loads(html)
					lon_data = len(data["cargos_actuales"])
					for x in range(0, lon_data):
						print colores.HEADER + "[URL TARGET] " + colores.normal + url
						print colores.verde + "[INFO] Target Name: " + colores.normal + data["name"]
						print colores.verde + "|----[INFO] Business: " + colores.normal + data["cargos_actuales"][x]["name"]
						print colores.verde + "|----[INFO] Date From: " + colores.normal + data["cargos_actuales"][x]["date_from"]
						print colores.verde + "|----[INFO] Title: " + colores.normal + data["cargos_actuales"][x]["title"]
			except:
				pass 
Example #12
Source File: typosquat.py    From ODIN with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def check_availability(self,domain):
        """Check whether or not the domain is registered.

        Parameters:
        domain      The domain name to be checked
        """
        try:
            who = whois.whois(domain)
            if who['status']:
                return True
            else:
                return False
        except:
            return False 
Example #13
Source File: domain_stats.py    From Logstash with GNU General Public License v3.0 5 votes vote down vote up
def main():
    parser=argparse.ArgumentParser()
    parser.add_argument('-ip','--address',required=False,help='IP Address for the server to listen on.  Default is 127.0.0.1',default='127.0.0.1')
    parser.add_argument('-c','--cache_time',type=float,required=False,help='Number of hours to hold a whois record in the cache. Default is 1 hour. Set to 0 to save forever.',default=1)
    parser.add_argument('port',type=int,help='You must provide a TCP Port to bind to')
    parser.add_argument('-v','--verbose',action='count',required=False,help='Print verbose output to the server screen.  -vv is more verbose.')
    parser.add_argument('-a','--alexa',required=False,help='Provide a local file path to an Alexa top-1m.csv')

    #args = parser.parse_args("-s 1 -vv 8081 english_lowercase.freq".split())
    args = parser.parse_args()

    #Setup the server.
    server = ThreadedDomainStats((args.address, args.port), domain_api)
    if args.alexa:
        if not os.path.exists(args.alexa):
            print("Alexa file not found %s" % (args.alexa))
        else:
            try:
                server.alexa = dict([(a,b) for b,a in re.findall(r"^(\d+),(.*)", open(args.alexa).read(), re.MULTILINE)])
            except Exception as e:
                print("Unable to parse alexa file:%s" % (str(e)))
    server.verbose = args.verbose
    server.cache_time = args.cache_time
    #Schedule the first save interval unless save_interval was set to 0.
    if args.cache_time:
        server.timer = threading.Timer(60 *args.cache_time, server.clear_old_cache, args = ())
        server.timer.start()
 
    #start the server
    print('Server is Ready. http://%s:%s/?cmd=measure&tgt=astring' % (args.address, args.port))
    print('[?] - Remember: If you are going to call the api with wget, curl or something else from the bash prompt you need to escape the & with \& \n\n')
    while True:
        try:
            server.handle_request()
        except KeyboardInterrupt:
            break

    server.timer.cancel()    
    server.safe_print("Web API Disabled...")
    server.safe_print("Control-C hit: Exiting server.  Please wait..") 
Example #14
Source File: whois.py    From arissploit with GNU General Public License v3.0 5 votes vote down vote up
def run():
	# Run
	w = whois.whois(variables["target"][0])
	print(w)
	return w 
Example #15
Source File: gasmask.py    From gasmask with GNU General Public License v3.0 5 votes vote down vote up
def WhoisQuery(value):
    whoisData = collections.OrderedDict()
    whoisData["name"] = ["-", "Name:"]
    whoisData["org"] = ["-", "Organization:"]
    whoisData["address"] = ["-", "Address:"]
    whoisData["city"] = ["-", "City:"]
    whoisData["zipcode"] = ["-", "Zip code:"]
    whoisData["country"] = ["-", "Country:"]
    whoisData["emails"] = ["-", "Emails:"]
    whoisData["registrar"] = ["-", "Registrar:"]
    whoisData["whois_server"] = ["-", "Whois Server:"]
    whoisData["updated_date"] = ["-", "Updated Date:"]
    whoisData["expiration_date"] = ["-", "Expiration Date:"]
    whoisData["creation_date"] = ["-", "Creation Date:"]
    whoisData["name_servers"] = ["-", "Name Servers:"]

    domain = whois.whois(value)

    for rec in whoisData:
        if domain[rec]:
            if isinstance(domain[rec], list):
                if rec == 'name_servers':
                    whoisData[rec][0] = []
                    for val in domain[rec]:
                        whoisData[rec][0].append(val + ":" + VerifyHostname(val))
                else:
                    whoisData[rec][0] = []
                    for val in domain[rec]:
                        whoisData[rec][0].append(val)
            else:
                whoisData[rec][0] = str(domain[rec])

    return whoisData 
Example #16
Source File: pureblood.py    From pureblood with MIT License 5 votes vote down vote up
def whois(self, w_url):
        try:
            whois_query = whois.whois(w_url)
            self.whois_result = whois_query
            return self.whois_result
        except:
            print("Could not find perform whois") 
Example #17
Source File: whoisleak.py    From Whoisleak with MIT License 5 votes vote down vote up
def searching(url):

	search = whois.whois(url)
	return search.email 
Example #18
Source File: info_s.py    From bane with MIT License 5 votes vote down vote up
def who_is(u):
 u=u.replace('www.','')
 try:
  return whois.whois(u)
 except:
  pass
 return {} 
Example #19
Source File: domain_check.py    From king-phisher-plugins with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def signal_precheck(self, mailer_tab):
		email = str(self.application.config['mailer.source_email'])
		user, _, domain = email.partition('@')
		self.logger.debug("checking email domain: {0}".format(domain))

		if not domain_has_mx_record(domain):
			response = gui_utilities.show_dialog_yes_no(
				'Invalid Email Domain',
				self.application.get_active_window(),
				'The source email domain does not exist. Continue?'
			)
			if not response:
				return False

		text_insert = mailer_tab.tabs['send_messages'].text_insert
		text_insert("Checking the WHOIS record for domain '{0}'... ".format(domain))
		try:
			info = whois.whois(domain)
		except Exception as error:
			text_insert("done, encountered exception: {0}.\n".format(error.__class__.__name__))
			self.logger.error("whois lookup failed for domain: {0}".format(domain), exc_info=True)
			response = gui_utilities.show_dialog_info(
				'Whois Lookup Failed',
				self.application.get_active_window(),
				'The domain is valid, however the whois lookup failed. Continue?'
			)
			return response

		if any(info.values()):
			text_insert('done, record found.\nWHOIS Record Overview:\n')
			text_insert("  Domain registered to: {0!r}\n".format(info.name))
			if info.name_servers:
				text_insert("  Name Servers:         {0}\n".format(', '.join(info.name_servers)))
			if info.emails:
				text_insert("  Contact Email:        {0}\n".format(info.emails))
		else:
			text_insert('done, no record found.\n')
		return True 
Example #20
Source File: PhishingKitHunter.py    From PhishingKitHunter with GNU Affero General Public License v3.0 5 votes vote down vote up
def whois_enrich(ex_url):
    global domain_registrar
    global domain_creat_date
    global domain_expi_date
    global resolv_dns
    resolv_dns = 'NOK'
    try:
        domreq = whois.whois(ex_url)
        if domreq.registrar is not None:
            domain_registrar = domreq.registrar
        else:
            domain_registrar = 'Not found'

        if domreq.creation_date is not None:
            if type(domreq.creation_date) is list:
                # First occurence is UTC creation date
                domain_creat_date = str(domreq.creation_date[0])
            else:
                domain_creat_date = domreq.creation_date
        else:
            domain_creat_date = 'None found'

        if domreq.expiration_date is not None:
            if type(domreq.expiration_date) is list:
                # First occurence is UTC expiration date
                domain_expi_date = str(domreq.expiration_date[0])
            else:
                domain_expi_date = domreq.expiration_date
        else:
            domain_expi_date = 'None found'
        resolv_dns = 'OK'
    except Exception as e:
        print(e)
        pass


# HTTP Get 
Example #21
Source File: whois.py    From omnibus with MIT License 5 votes vote down vote up
def fqdn(self):
        try:
            results = whois.whois(self.artifact['name'])
            self.artifact['data']['whois'] = results
        except:
            pass 
Example #22
Source File: whois.py    From omnibus with MIT License 5 votes vote down vote up
def ip(self):
        whois_data = IPWhois(self.artifact['name'])

        try:
            data = whois_data.lookup_whois()

            if data is not None:
                self.artifact['data']['whois'] = {}

                # collect ASN information

                self.artifact['data']['whois']['asn'] = data['asn']
                self.artifact['data']['whois']['asn']['cidr'] = data['asn_cidr']
                self.artifact['data']['whois']['asn']['description'] = data['asn_description']
                self.artifact['data']['whois']['asn']['country'] = data['asn_country_code']

                if 'nets' in data.keys() and len(data['nets']) > 0:
                    net_data = data['nets'][0]
                    self.artifact['data']['whois']['address'] = net_data['address']
                    self.artifact['data']['whois']['state'] = net_data['state']
                    self.artifact['data']['whois']['emails'] = net_data['emails']

        except Exception as err:
            warning('Caught unhandled exception: %s' % str(err)) 
Example #23
Source File: whois.py    From omnibus with MIT License 5 votes vote down vote up
def __init__(self, artifact):
        self.artifact = artifact
        self.artifact['data']['whois'] = None 
Example #24
Source File: test_query.py    From whois with MIT License 5 votes vote down vote up
def test_ipv6(self):
        """ Verify ipv6 addresses. """
        domain = '2607:f8b0:4006:802::200e'
        whois_results = whois(domain)
        if isinstance(whois_results['domain_name'], list):
            domain_names = [_.lower() for _ in whois_results['domain_name']]
        else:
            domain_names = [whois_results['domain_name'].lower()]

        self.assertIn('1e100.net', domain_names)
        self.assertIn('ns1.google.com', [_.lower() for _ in whois_results['name_servers']]) 
Example #25
Source File: test_query.py    From whois with MIT License 5 votes vote down vote up
def test_ipv4(self):
        """ Verify ipv4 addresses. """
        domain = '172.217.3.110'
        whois_results = whois(domain)
        if isinstance(whois_results['domain_name'], list):
            domain_names = [_.lower() for _ in whois_results['domain_name']]
        else:
            domain_names = [whois_results['domain_name'].lower()]

        self.assertIn('1e100.net', domain_names)
        self.assertIn('ns1.google.com', [_.lower() for _ in whois_results['name_servers']]) 
Example #26
Source File: test_query.py    From whois with MIT License 5 votes vote down vote up
def test_unicode_domain_and_tld(self):
        domain = 'россия.рф'
        whois(domain) 
Example #27
Source File: test_query.py    From whois with MIT License 5 votes vote down vote up
def test_simple_unicode_domain(self):
        domain = 'нарояци.com'
        whois(domain) 
Example #28
Source File: test_query.py    From whois with MIT License 5 votes vote down vote up
def test_simple_ascii_domain(self):
        domain = 'google.com'
        whois(domain) 
Example #29
Source File: domain_whois.py    From datasploit with GNU General Public License v3.0 5 votes vote down vote up
def whoisnew(domain):
	try:
	    w = whois.whois(domain)
	    return dict(w)
	except:
		return {} 
Example #30
Source File: whois_search.py    From punter with The Unlicense 5 votes vote down vote up
def whois_target(host):

    # Technically this is still passive recon
    # because you still aren't hitting target
    w = whois.whois(host)

    return w.text, w.emails, w