Python ipwhois.IPWhois() Examples

The following are 30 code examples of ipwhois.IPWhois(). 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 ipwhois , or try the search function .
Example #1
Source File: dnsutils.py    From maltelligence with GNU General Public License v3.0 6 votes vote down vote up
def get_asn2(data):
    #   find as number with ipwhois modules
    if chk_domain(data):
        ip, c_name = retIP(data)
    if chk_ip(data):
        ip = data
    
    obj = IPWhois(ip)
    results = obj.lookup()
    as_number = 0
    subnet = ''
    try:
        if results.has_key('asn'):
            as_number = int(results['asn'])
    except:
        pass
    if results.has_key('asn_cidr'):
        subnet = results['asn_cidr']
    return as_number, subnet 
Example #2
Source File: favUp.py    From fav-up with MIT License 6 votes vote down vote up
def deepConnectionLens(self, response):
        mIP = 'not-found'
        mISP = 'not-found'
        if response.status_code == 200:
            try:
                mIP = list(response.raw._connection.sock.getpeername())[0]
                mISP = IPWhois(mIP).lookup_whois()['nets'][0]['name']
            except AttributeError:
                try:
                    mIP = list(response.raw._connection.sock.socket.getpeername())[0]
                    mISP = IPWhois(mIP).lookup_whois()['nets'][0]['name']
                except AttributeError:
                    pass
        if mIP == 'not-found':
            self._iterator.write(f"[x] There's problem when getting icon for {response.url.split('/')[2]} with status code: {response.status_code}" )
        return {
            'mIP': mIP,
            'mISP': mISP
        } 
Example #3
Source File: helper.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def get_rdap_registry_info(ip_input, rdap_depth):
    """Gathers registry info in RDAP protocol

    Arguments:
        ip_input {string} -- Artifact.value
        rdap_depth {int} -- 0,1 or 2

    Returns:
        {object} -- Registry info, RDAP Protocol
    """
    try:
        internet_protocol_address_object = IPWhois(ip_input,allow_permutations=True)
        try:
            rdap_response = internet_protocol_address_object.lookup_rdap(rdap_depth)
            if internet_protocol_address_object.dns_zone:
                rdap_response["dns_zone"] = internet_protocol_address_object.dns_zone
            return rdap_response
        except exceptions.ASNRegistryError as e:
            logging.error(traceback.format_exc())
    except:
        logging.error(traceback.format_exc()) 
Example #4
Source File: helper.py    From resilient-community-apps with MIT License 6 votes vote down vote up
def get_whois_registry_info(ip_input):
    """Gather registry information
    Arguments:
        ip_input {string} -- Artifact.value
    Returns:
        {object} -- Contains all registry information
    """
    try:
        internet_protocol_address_object = IPWhois(ip_input,allow_permutations=True)
        try:
            whois_response = internet_protocol_address_object.lookup_whois()
            if internet_protocol_address_object.dns_zone:
                whois_response["dns_zone"] = internet_protocol_address_object.dns_zone
            return whois_response
        except exceptions.ASNRegistryError as e:
            logging.error(traceback.format_exc())
    except:
        logging.error(traceback.format_exc()) 
Example #5
Source File: lookup.py    From vault with MIT License 6 votes vote down vote up
def whois_lookup(ip):
    """Perform Whois lookup for a given IP
        :ip: Ip to peform whois lookup
    """
    colors.info('Performing WHOIS lookup')
    obj = IPWhois(ip)
    response = obj.lookup_whois()
    details = response['nets'][0]
    name = details['name']
    city = details['city']
    state = details['state']
    country = details['country']
    address = details['address']
    description = details['description']

    return {'Name': name, 'City': city, 'State': state,
            'Country': country, 'address': address, 'description': description} 
Example #6
Source File: sentry.py    From marvin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_ip_dict(self, ip, method='whois'):
        ''' Get the ip lookup dictionary '''

        if not ipwhois:
            raise ImportError('Cannot look up ips.  You do not have the ipwhois package installed!')

        assert method in ['whois', 'rdap'], 'Method must either be rdap or whois'

        ipwho = ipwhois.IPWhois(ip)
        self.ipmethod = method
        ipdict = None
        if method == 'whois':
            try:
                ipdict = ipwho.lookup_whois()
            except Exception as e:
                print('Could not lookup ip {0}: {1}'.format(ip, e))
        elif method == 'rdap':
            try:
                ipdict = ipwho.lookup_rdap()
            except Exception as e:
                print('Could not lookup ip {0}: {1}'.format(ip, e))
        return ipdict 
Example #7
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 #8
Source File: ipwhois.py    From machinae with MIT License 6 votes vote down vote up
def get_json(self):
        obj = ipwhois.IPWhois(self.kwargs["target"])
        try:
            # import json
            # print(json.dumps(obj.lookup_rdap(depth=2)))
            # return obj.lookup_rdap(depth=2)
            return obj.lookup_rws()
        except AttributeError:
            # rdap = obj.lookup_rdap(inc_raw=True)
            # print(json.dumps(rdap))
            # rdap["network"]["range"] = "{start_address} - {end_address}".format(**rdap["network"])
            # rdap["network"]["cidr"] = self.get_cidr(rdap["network"])
            # return rdap
            # RDAP is a stupid format, use raw whois
            raw = obj.lookup()
            print(raw)
            return raw 
Example #9
Source File: Sooty.py    From Sooty with GNU General Public License v3.0 5 votes vote down vote up
def whoIsPrint(ip):
    try:
        w = IPWhois(ip)
        w = w.lookup_whois()
        addr = str(w['nets'][0]['address'])
        addr = addr.replace('\n', ', ')
        print("\n WHO IS REPORT:")
        print("  CIDR:      " + str(w['nets'][0]['cidr']))
        print("  Name:      " + str(w['nets'][0]['name']))
       # print("  Handle:    " + str(w['nets'][0]['handle']))
        print("  Range:     " + str(w['nets'][0]['range']))
        print("  Descr:     " + str(w['nets'][0]['description']))
        print("  Country:   " + str(w['nets'][0]['country']))
        print("  State:     " + str(w['nets'][0]['state']))
        print("  City:      " + str(w['nets'][0]['city']))
        print("  Address:   " + addr)
        print("  Post Code: " + str(w['nets'][0]['postal_code']))
       # print("  Emails:    " + str(w['nets'][0]['emails']))
        print("  Created:   " + str(w['nets'][0]['created']))
        print("  Updated:   " + str(w['nets'][0]['updated']))
        c = 0
    except:
        print("\n  IP Not Found - Checking Domains")
        ip = re.sub('https://', '', ip)
        ip = re.sub('http://', '', ip)
        try:
            if c == 0:
                s = socket.gethostbyname(ip)
                print( '  Resolved Address: %s' % s)
                c = 1
                whoIsPrint(s)
        except:
            print(' IP or Domain not Found')
    return 
Example #10
Source File: whois.py    From python-tools with MIT License 5 votes vote down vote up
def whois(url):
    """Get WHOIS from IP address or hostname.

    Args:
        url (str): IP address or hostname.

    Returns:
        dict: Return a JSON object with the WHOIS.

    """
    url = url.strip()
    if not parse.urlparse(url).scheme:
        url = 'http://' + url
    host = parse.urlparse(url).netloc
    try:
        ipaddress.ip_address(host)
        ip = host
    except Exception:
        try:
            ips = resolver.query(host, 'A')
            ip = ips[0]
        except Exception:
            return {}

    obj = IPWhois(ip)
    return obj.lookup_whois() 
Example #11
Source File: node.py    From EasyStorj with MIT License 5 votes vote down vote up
def node_details(self, nodeID):
        node_details_array = {}
        self.node_details_content = storj_engine.storj_client.contact_lookup(str(nodeID))

        node_details_array["address"] = self.node_details_content.address
        node_details_array["lastTimeout"] = self.node_details_content.lastTimeout
        node_details_array["timeoutRate"] = self.node_details_content.timeoutRate
        node_details_array["userAgent"] = self.node_details_content.userAgent
        node_details_array["protocol"] = self.node_details_content.protocol
        node_details_array["responseTime"] = self.node_details_content.responseTime
        node_details_array["lastSeen"] = self.node_details_content.lastSeen
        node_details_array["port"] = self.node_details_content.port
        node_details_array["nodeID"] = self.node_details_content.nodeID

        ip_addr = socket.gethostbyname(str(self.node_details_content.address))

        obj = IPWhois(ip_addr)
        res = obj.lookup_whois()
        country = res["nets"][0]['country']

        country_parsed = pycountry.countries.get(alpha_2=str(country))

        country_full_name = country_parsed.name

        node_details_array["country_full_name"] = country_full_name
        node_details_array["country_code"] = country

        return node_details_array 
Example #12
Source File: controller.py    From EasyStorj with MIT License 5 votes vote down vote up
def whois_lookup_country (address):

    IP_addr = socket.gethostbyname(str(address))
    obj = IPWhois(IP_addr)
    res = obj.lookup_whois()
    country = res["nets"][0]['country']

    return country 
Example #13
Source File: helpers.py    From Tautulli with GNU General Public License v3.0 5 votes vote down vote up
def whois_lookup(ip_address):

    nets = []
    err = None
    try:
        whois = ipwhois.IPWhois(ip_address).lookup_whois(retry_count=0)
        countries = ipwhois.utils.get_countries()
        nets = whois['nets']
        for net in nets:
            net['country'] = countries.get(net['country'])
            if net['postal_code']:
                 net['postal_code'] = net['postal_code'].replace('-', ' ')
    except ValueError as e:
        err = 'Invalid IP address provided: %s.' % ip_address
    except ipwhois.exceptions.IPDefinedError as e:
        err = '%s' % e
    except ipwhois.exceptions.ASNRegistryError as e:
        err = '%s' % e
    except Exception as e:
        err = 'Error: %s' % e

    host = ''
    try:
        host = ipwhois.Net(ip_address).get_host(retry_count=0)[0]
    except Exception as e:
        host = 'Not available'

    whois_info = {"host": host,
                  "nets": nets
                  }

    if err:
        whois_info['error'] = err

    return whois_info


# Taken from SickRage 
Example #14
Source File: ipwhois.py    From Verum with Apache License 2.0 5 votes vote down vote up
def run(self, domain, start_time=""):
        """ str, str -> networkx multiDiGraph

        :param domain: a string containing a domain to look up
        :param start_time: string in ISO 8601 combined date and time format (e.g. 2014-11-01T10:34Z) or datetime object.
        :return: a networkx graph representing the whois information about the domain
        """
        ip = socket.gethostbyname(domain)  # This has a habit of failing
        record = [None] * 10
        obj = IPWhois(ip)
        results = obj.lookup()

        nets = results.pop("nets")

        for i in range(len(nets)):
            net = nets[i]
            record[0] = i
            if "updated" in net:
                record[1] = net['updated'][:10]
            elif "created" in net:
                record[1] = net['created'][:10]
            record[2] = domain
            if "name" in net:
                record[3] = net['name']
            if "organization" in net:
                record[4] = net['organization']
            if 'address' in net:
                record[5] = net['address']
            if 'city' in net:
                record[6] = net['city']
            if 'state' in net:
                record[7] = net['state']
            if 'country' in net:
                record[8] = net['country']
            if 'misc_emails' in net and net['misc_emails'] is not None:
                emails = net['misc_emails'].split("\n")
                record[9] = emails[0]

            return self.enrich_record(record, start_time) 
Example #15
Source File: communicationDetailsFetch.py    From PcapXray with GNU General Public License v2.0 5 votes vote down vote up
def whois_info_fetch(self, ip, ips):
       for i in ips:
         if "whois" not in self.communication_details[ip]["ip_details"][i]:
             self.communication_details[ip]["ip_details"][i]["whois"] = ""
         try:
            whois_info = ipwhois.IPWhois(ip).lookup_rdap()
         except:
            whois_info = "NoWhoIsInfo"
         self.communication_details[ip]["ip_details"][i]["whois"] = whois_info 
Example #16
Source File: ip_whois.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def handle_command(self, parameters):
        response = ""
        for ip_token in parameters:
            if is_ip(ip_token):
                ip = netaddr.IPNetwork(ip_token)[0]
                if (not ip.is_loopback() and not ip.is_private() and not ip.is_reserved()):
                    whois = IPWhois(ip).lookup_whois()
                    description = whois['nets'][0]['description']
                    response += "{0} description: {1}\n".format(ip_token, description)
                else:
                    response += "{0}: hrm...loopback? private ip?\n".format(ip_token)
            else:
                response = "{0} is not an IP address".format(ip_token)
        return response 
Example #17
Source File: index.py    From MozDef with Mozilla Public License 2.0 5 votes vote down vote up
def getWhois(ipaddress):
    try:
        whois = dict()
        ip = netaddr.IPNetwork(ipaddress)[0]
        if (not ip.is_loopback() and not ip.is_private() and not ip.is_reserved()):
            whois = IPWhois(netaddr.IPNetwork(ipaddress)[0]).lookup_whois()

        whois['fqdn']=socket.getfqdn(str(netaddr.IPNetwork(ipaddress)[0]))
        return (json.dumps(whois))
    except Exception as e:
        logger.error('Error looking up whois for {0}: {1}\n'.format(ipaddress, e)) 
Example #18
Source File: whois.py    From ACF with Apache License 2.0 5 votes vote down vote up
def run(self):
        try:
            ip_whois = IPWhois(self._dst_ip)
            raw_res = ip_whois.lookup()
            res = []
            for k,v in raw_res.iteritems():
                if not v is None:
                    res.append("%s: %s" % (k,v))
            return ",".join(res)
        except Exception, e:
             return "" 
Example #19
Source File: communication_details_fetch.py    From PcapXray with GNU General Public License v2.0 5 votes vote down vote up
def whois_info_fetch(self, ip):
        try:
           whois_info = ipwhois.IPWhois(ip).lookup_rdap()
        except:
           whois_info = "NoWhoIsInfo"
        return whois_info 
Example #20
Source File: whois_info.py    From Just-Metadata with GNU General Public License v3.0 5 votes vote down vote up
def gather(self, all_ips):

        for path, incoming_ip_obj in all_ips.iteritems():

            if incoming_ip_obj[0].ip_whois == "" and incoming_ip_obj[0].ip_address != "":

                try:
                    print "Gathering whois information about " + incoming_ip_obj[0].ip_address
                    ip_whois = IPWhois(incoming_ip_obj[0].ip_address)
                    incoming_ip_obj[0].ip_whois = ip_whois.lookup_whois()
                except IPDefinedError:
                    print helpers.color("[*] Error: Private IP address, skipping IP!", warning=True)
                except HTTPLookupError:
                    print helpers.color("Could not connect online to lookup whois for " + incoming_ip_obj[0].domain_name, warning=True)
        return 
Example #21
Source File: __init__.py    From aegea with Apache License 2.0 5 votes vote down vote up
def describe_cidr(cidr):
    import ipwhois, ipaddress, socket
    address = ipaddress.ip_network(str(cidr)).network_address
    try:
        whois = ipwhois.IPWhois(address).lookup_rdap()
        whois_names = [whois["asn_country_code"]] if "asn_country_code" in whois else []
        whois_names += [o.get("contact", {}).get("name", "") for o in whois.get("objects", {}).values()]
    except Exception:
        try:
            whois_names = [socket.gethostbyaddr(address)]
        except Exception:
            whois_names = [cidr]
    return ", ".join(str(n) for n in whois_names) 
Example #22
Source File: mimir.py    From Mimir with GNU General Public License v3.0 5 votes vote down vote up
def whois():
	print "[" + t.green("+") + "]Please provide an IP for WHOIS lookup."
	TARGET = raw_input("\n<" + t.cyan("WHOIS") + ">$ ")
	
	obj = IPWhois(TARGET)
	results = obj.lookup_rdap(depth=1)
	pprint(results)
	
	print "\n[" + t.magenta("?") + "]Would you like to append the WHOIS record to a text file?\n"
	logs = raw_input("[Y]es/[N]o: ").lower()
	
	format = json.dumps(results, indent = 2)
	
	if logs == "y":
		with open( "whois.log", "ab" ) as outfile:
			outfile.write("Host: " + TARGET + "\n")
			outfile.write(format)
			outfile.close()
			
		print "[" + t.green("+") + "]Results saved to whois.log in the current directory.\n"
			
	elif logs == "n":
		print "[" + t.green("+") + "]Returning to main menu.\n"
		
	else:
		print "[" + t.red("!") + "]Unhandled Option.\n" 
Example #23
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 #24
Source File: scrambler.py    From cachebrowser with MIT License 5 votes vote down vote up
def _whois(ip, org_names):
    from ipwhois import IPWhois

    if type(ip) is not str:
        ip = _get_flow_ip(ip)

    if ip not in _whois_cache:
        whois = IPWhois(ip)
        try:
            name = whois.lookup_rdap()['network']['name']
            if not name:
                name = whois.lookup()['nets'][0]['name']
        except:
            print("WHOIS ERROR")
            name = 'OTHER'

        _whois_cache[ip] = _clean_netname(org_names, name, ip)
    return _whois_cache[ip] 
Example #25
Source File: whois_collector.py    From AttackSurfaceMapper with GNU General Public License v3.0 5 votes vote down vote up
def wlookup(hostx):
    for ip in hostx.resolved_ips:
        try:
            ip_object = IPWhois(ip.address)
            query = ip_object.lookup_rdap(depth=1)
            #            hostx.whois.append(query)
            #            net_sec = query.get('network', {})
            ip.location = query.get('asn_country_code')
            ip.asn = query.get('asn')
            ip.cidr = query.get('asn_cidr')
        #            print("Executed")
        #            print(query['network']['name'])
        except:
            pass 
Example #26
Source File: blockcheck.py    From blockcheck with MIT License 5 votes vote down vote up
def get_ispinfo(ipaddr):
    try:
        rdap_response = ipwhois.IPWhois(ipaddr)
        ispinfo = rdap_response.lookup_rdap(depth=1)
        return ispinfo['asn']
    except (ipwhois.exceptions.ASNRegistryError,
            ipwhois.exceptions.ASNLookupError,
            ipwhois.exceptions.ASNParseError,
            ipwhois.exceptions.HTTPLookupError,
            ipwhois.exceptions.HTTPRateLimitError):
        return False 
Example #27
Source File: ip_whois.py    From datasploit with GNU General Public License v3.0 5 votes vote down vote up
def main(ip):
    obj = IPWhois(ip)
    try:
        results = obj.lookup_rdap(depth=1)
    except:
        results = None
    return results 
Example #28
Source File: scanner.py    From aztarna with GNU General Public License v3.0 5 votes vote down vote up
def get_address_info(self, routers):
        """
        Get country code and ASN description based on the routers IP address.
        :param routers:
        :return:
        """
        for router in routers:
            if isinstance(router, self.__class__.router_cls):
                try:
                    whois = IPWhois(router.address)
                    results = whois.lookup_rdap(depth=1)
                    if results['asn_country_code']:
                        router.country = results['asn_country_code']
                    if results['asn_description']:
                        router.asn_description = results['asn_description']
                except:
                    pass 
Example #29
Source File: whois.py    From FinalRecon with MIT License 5 votes vote down vote up
def whois_lookup(ip, output, data):
	collect = {}
	print ('\n' + Y + '[!]' + Y + ' Whois Lookup : ' + W + '\n')
	try:
		lookup = ipwhois.IPWhois(ip)
		results = lookup.lookup_whois()

		for k,v in results.items():
			if v != None:
				if isinstance(v, list):
					for item in v:
						for k, v in item.items():
							if v != None:
								print (G + '[+]' + C + ' {} : '.format(str(k)) + W + str(v).replace(',', ' ').replace('\r', ' ').replace('\n', ' '))
								if output != 'None':
									collect.update({str(k):str(v).replace(',', ' ').replace('\r', ' ').replace('\n', ' ')})
							else:
								pass
				else:
					print (G + '[+]' + C + ' {} : '.format(str(k)) + W + str(v).replace(',', ' ').replace('\r', ' ').replace('\n', ' '))
					if output != 'None':
						collect.update({str(k):str(v).replace(',', ' ').replace('\r', ' ').replace('\n', ' ')})
			else:
				pass
	
	except Exception as e:
		print (R + '[-] Error : ' + C + str(e) + W)
		if output != 'None':
			collect.update({'Error':str(e)})
		pass
	
	if output != 'None':
		whois_output(output, data, collect) 
Example #30
Source File: network_whois.py    From yeti with Apache License 2.0 4 votes vote down vote up
def analyze(ip, results):
        links = set()

        r = IPWhois(ip.value)
        result = r.lookup_whois()
        results.update(raw=pformat(result))

        # Let's focus on the most specific information
        # Which should be in the smallest subnet
        n = 0
        smallest_subnet = None

        for network in result['nets']:
            cidr_bits = int(network['cidr'].split('/')[1].split(',')[0])
            if cidr_bits > n:
                n = cidr_bits
                smallest_subnet = network

        if smallest_subnet:
            # Create the company
            company = Company.get_or_create(
                name=smallest_subnet['description'].split("\n")[0])
            links.update(ip.active_link_to(company, 'hosting', 'Network Whois'))

            # Link it to every email address referenced
            if smallest_subnet['emails']:
                for email_address in smallest_subnet['emails']:
                    email = Email.get_or_create(value=email_address)
                    links.update(company.link_to(email, None, 'Network Whois'))

            # Copy the subnet info into the main dict
            for key in smallest_subnet:
                if smallest_subnet[key]:
                    result["net_{}".format(key)] = smallest_subnet[key]

        # Add the network whois to the context if not already present
        for context in ip.context:
            if context['source'] == 'network_whois':
                break
        else:
            # Remove the nets info (the main one was copied)
            result.pop("nets", None)
            result.pop("raw", None)
            result.pop("raw_referral", None)
            result.pop("referral", None)
            result.pop("query", None)

            result['source'] = 'network_whois'
            ip.add_context(result)

        return list(links)