예제 #1
0
def get_whois_ip(ip,refresh=None):
	es = Elasticsearch()
	print repr(ip)
	id_num = str(ip).replace(".","0")
	does_exist = es.exists(index='rwhois2', doc_type='ipaddr', id = id_num)
	print does_exist
	if does_exist is True and refresh is None:
		status = 200
		print "Found it!"
		get_record = es.get(index='rwhois2',doc_type='ipaddr', id = id_num)
		results = jsonify(get_record['_source'])
	elif does_exist is True and refresh is not None:
                status = 200
                print "Forcing refresh!"
                es.delete(index='rwhois2', doc_type='ipaddr', id = id_num)
                try:
                        ipwhois.net.socks.setdefaultproxy(ipwhois.net.socks.SOCKS5,"localhost")
			obj = IPWhois(ip)
                        try:
                                results_raw = obj.lookup_whois(get_referral=True,inc_nir=True)
                        except:
                                results_raw = obj.lookup_whois()

                        status = 200
                        results = jsonify(results_raw)
                        es.index(index='rwhois2', doc_type='ipaddr', id=id_num, body=results_raw)

                except Exception as e:
                        print e
                        results = jsonify({'status': "not_found"})
                        status = 404


	
	else:
		try:
			obj = IPWhois(ip)
			try:
				results_raw = obj.lookup_whois(get_referral=True)
			except:
				results_raw = obj.lookup_whois()
			status = 200
			results = jsonify(results_raw)
			id_num = str(ip).replace(".","0")
                        print results
                        try:
				es.index(index='rwhois2', doc_type='ipaddr', id=id_num, body=results_raw)
			except Exception as e:
				print "Elasticsearch encountered a problem ", e
                                pass
		except Exception as e:
                        #print results_raw
        	        print e
                	results_raw = jsonify({'status': "not_found"})
	                status = 404
        	        results = jsonify({'status': "not_found"})
        return results,status
예제 #2
0
def get_whois_info(ip_str: str,
                   show_progress: bool = False) -> Tuple[str, dict]:
    """
    Retrieve whois ASN information for given IP address using IPWhois python package.

    Parameters
    ----------
    ip_str : str
        IP Address to look up.
    show_progress : bool, optional
        Show progress for each query, by default False

    Returns
    -------
    IP
        Details of the IP data collected

    Notes
    -----
    This function uses the Python functools lru_cache and
    will return answers from the cache for previously queried
    IP addresses.

    """
    ip_type = get_ip_type(ip_str)
    if ip_type == "Public":
        whois = IPWhois(ip_str)
        whois_result = whois.lookup_whois()
        if show_progress:
            print(".", end="")
        return whois_result["asn_description"], whois_result
    return f"No ASN Information for IP type: {ip_type}", {}
    def __init__(self):

        print('Welcome to IP Scanner: ')
        target = input('Enter the IP which you want to scan: ')
        ip = IPWhois(target)
        resolve = IPWhois.lookup_whois(ip)
        pprint(resolve)
예제 #4
0
def whois(ip):
    data = IPWhois(ip, timeout=15)
    data = data.lookup_whois()
    country = data['nets'][0]['country']
    city = data['nets'][0]['city']
    address = data['nets'][0]['address']
    return {'city': city, 'country': country, 'address': address}
예제 #5
0
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']))
    except:
        print("\n  IP Not Found - Checking Domains")
        ip = re.sub('https://', '', ip)
        ip = re.sub('http://', '', ip)
        try:
            s = socket.gethostbyname(ip)
            print('  Resolved Address: %s' % s)
            whoIsPrint(s)
        except:
            print(' IP or Domain not Found')
    return
예제 #6
0
def main():

    with open('results.csv') as csvfile:
        readCSV = csv.reader(csvfile, delimiter=',')
        ip_cidr = {}
        for row in readCSV:
            ip = row[0]
            print(ip)
            obj = IPWhois(row[0])
            try:
                resp = obj.lookup_whois()
                cidr = resp["nets"][0]['cidr']
                print("CIDR: ", cidr)
                #print("IP Range: ", [str(ip) for ip in ipaddress.IPv4Network(cidr)])
                ip_cidr[ip] = cidr
                # group ip with the same cidr
            except Exception:
                print("skipped ", ip)
            ip_cidr_grouped = defaultdict(list)

            for key, value in ip_cidr.items():
                ip_cidr_grouped[value].append(key)

        for key, value in ip_cidr_grouped.items():
            print(key, "=>", value)
def whois1(ip):
    ans = ""
    try:
        obj = IPWhois(ip)
    except ipwhois.exceptions.IPDefinedError:
        res = {}
    else:
        try:
            res = obj.lookup_whois()
        except ipwhois.exceptions.ASNRegistryError:
            res = {}

    if (res == {}):
        ans = ans + 'Private Network' + '\n'
        return ans
    j = 1
    for i in res:
        if i == 'nets':
            str1 = str(res[i])
            str1 = str1.split(",")
            for k in str1:
                ans = ans + '         ' + str(k) + ' \n '
        else:
            ans = ans + str(i) + ' : ' + str(res[i]) + ' \n '

        j = j + 1
    return ans
예제 #8
0
    def ipWho(self, renew=False):
        """
        fetch only basic asn and latest network data
        """
        if "asn_query_status" in self._response and not renew:
            return self._response

        try:
            obj = IPWhois(self._ip)
            self._rawResponse = obj.lookup_whois(inc_nir=True)
            self._response["asn_query_status"] = "ok"
        except:
            self._response["asn_query_status"] = "fail"
        self._response["asn_country"] = self._rawResponse["asn_country_code"]
        self._response["asn"] = self._rawResponse["asn"]
        if self._rawResponse["asn"]:
            key = "".join(["AS", self._rawResponse["asn"]])
            self._response["asn_name"] = self._ASN_DICT.get(key, "UNKOWN")
        if self._rawResponse["nets"]:
            ####get most recent net data
            net = sorted(self._rawResponse["nets"],
                         key=BasicIPWho.upis_date,
                         reverse=True)[0]
            self._response["net_description"] = net["description"]
            self._response["net_name"] = net["name"]
            self._response["net_updated"] = net["updated"]

        return self._response
예제 #9
0
파일: access_log.py 프로젝트: essans/RasPi
def src_details(ip_addr):

    src = {}

    if (ip_addr in ['None', '0.0.0.0']) or (ip_addr[0:7] == '192.168'):
        src['name'] = ''
        #src['descr'] = ''
        src['cntry'] = ''
        src['city'] = ''
        #src['state'] = ''
        src['addr'] = ''
        #src['emails'] = ''

    else:

        obj = IPWhois(ip_addr)
        res = obj.lookup_whois()

        src['name'] = res['nets'][0]['name']
        #src['descr'] = res['nets'][0]['description']

        src['cntry'] = res['nets'][0]['country']
        src['city'] = res['nets'][0]['city']
        #src['state'] = res['nets'][0]['state']

        #if scr['addr'] is not None:
        #	src['addr'] = res['nets'][0]['address'].replace('\n',',')
        #else:
        #	src['addr']=''

        #src['emails'] = str(res['nets'][0]['emails'])

    return src
예제 #10
0
    def ip_Lookup(
        c, t, max
    ):  # ------------------------------[     IP LOOKUP       ]--------------------
        with warnings.catch_warnings():
            warnings.filterwarnings("ignore", category=UserWarning)
            ip = str(c)

            add = host_by_name(ip)

            obj = IPWhois(add, 5)
            res = obj.lookup_whois()

            print("\n")
            print("IP Lookup results for '{0}' [{1}]".format(ip, add))
            for els in res:  #GET OBJ RESULT
                val = "{0}".format(els)
                res_els = res[val]
                if res_els is not None:  #IF ACTUAL OBJECT HAVE CONTENT
                    if val == 'nets':
                        nets_D = res_els[0]
                        for k in nets_D:  #GET KEYS OF DICTS TO VIEW CONTENT
                            content = nets_D.get(k)
                            result = "{0:<20} {1}".format(k, content)
                            print(result)  #RESULTS OF NETS INFORMATIONS
                    else:  #GET CONTENT IF IS NOT DICT
                        result = "{0:<20} {1}".format(els, res_els)
                        print(result)  #RESULTS OF COMMOM INFORMATIONS
            print("\n")
예제 #11
0
def whoIs():
    ip = raw_input(' Enter 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']))
    except:
        print(" IP Not Found")

    dnsMenu()
예제 #12
0
def ip_whois(dicsubdominios):
    for (k, v) in dicsubdominios.items():
        hosts = IPWhois(v)  # .lookup_rws()
        results = hosts.lookup_whois()
        print('Host: ', v)
        pprintpp.pprint(results)
        print('\n\n')
예제 #13
0
파일: ip_utils.py 프로젝트: yazici/msticpy
def get_whois_info(ip_str: str, show_progress=False) -> Tuple[str, dict]:
    """
    Retrieve whois ASN information for given IP address using IPWhois python package.

    Parameters
    ----------
    ip_str : str
        [description]
    show_progress : bool, optional
        [description], by default False

    Returns
    -------
    IP
        Details of the IP data collected

    """
    ip_type = get_ip_type(ip_str)
    if ip_type == "Public":
        whois = IPWhois(ip_str)
        whois_result = whois.lookup_whois()
        if show_progress:
            print(".", end="")
        return whois_result["asn_description"], whois_result
    else:
        return f"N ASN Information since IP address is of type: {ip_type}", {}
예제 #14
0
    def _handle_test_connectivity(self, param):

        ip = '1.1.1.1'

        action_result = self.add_action_result(ActionResult(dict(param)))

        action_result.set_param({phantom.APP_JSON_IP: ip})

        self.debug_print("Validating/Querying IP '{0}'".format(ip))

        self.save_progress("Querying...")

        try:
            obj_whois = IPWhois(ip)
            whois_response = obj_whois.lookup_whois(asn_methods=['whois', 'dns', 'http'])
        except IPDefinedError as e_defined:
            self.debug_print("Got IPDefinedError exception str: {0}".format(str(e_defined)))
            self.save_progress("Test Connectivity Failed")
            return action_result.set_status(phantom.APP_SUCCESS, str(e_defined))
        except Exception as e:
            error_message = self._get_error_message_from_exception(e)
            self.debug_print("Got exception: type: {0}, str: {1}".format(type(e).__name__, str(error_message)))
            self.save_progress("Test Connectivity Failed")
            return action_result.set_status(phantom.APP_ERROR, WHOIS_ERR_QUERY, error_message)

        if not whois_response:
            self.save_progress("Test Connectivity Failed")
            return action_result.set_status(phantom.APP_ERROR, WHOIS_ERR_QUERY_RETURNED_NO_DATA)

        self.save_progress("Test Connectivity Passed")
        return action_result.set_status(phantom.APP_SUCCESS)
def do_isp_routine(rows, isp, total, tid):
    global to_remove, do_isp_lock, count

    local_to_remove = []
    for row in rows:
        ip = str(row[0])
        obj = IPWhois(ip)
        try:
            res = obj.lookup_whois(False)
            for net in res['nets']:
                if not net['name'] is None and net['name'].lower().find(
                        isp) != -1:
                    local_to_remove.append(ip)
        except:
            pass

        do_isp_lock.acquire()
        count += 1
        print "%d: %d out of %d (%d%%)" % (tid, count, total,
                                           count * 100 / total)
        do_isp_lock.release()

    if len(local_to_remove) > 0:
        do_isp_lock.acquire()
        to_remove.extend(local_to_remove)
        do_isp_lock.release()
예제 #16
0
def get_nir(ipaddr):
    obj = IPWhois(ipaddr)
    NirInfo = obj.lookup_whois(inc_nir=True)

    if NirInfo is None:
        return 0
    else:
        return NirInfo
예제 #17
0
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
def ipLookup(ip):
    obj = IPWhois(ip)
    res = obj.lookup_whois()
    country = res["nets"][0]['country']
    description = res["nets"][0]['description']
    if description is None:
        description="None"
    return country, description
예제 #19
0
파일: __init__.py 프로젝트: rascal999/qad
def performWhoIs(IP):
    print()
    print(timeStamp() + "* Performing WHOIS on " + IP)
    obj = IPWhois(IP)
    res = obj.lookup_whois()
    print(timeStamp() + "- WHOIS name: " + res["nets"][0]['name'])
    print(timeStamp() + "- WHOIS CIDR: " + res['asn_cidr'])
    print(timeStamp() + "- More info at http://who.is/whois-ip/ip-address/" + IP)
예제 #20
0
def whois_single(domain):
    obj = IPWhois(domain)
    res = obj.lookup_whois(inc_nir=True)
    output = json.dumps(res)
    result = []
    for line in output.split('\n', 1):
        result.append(line)
    return result
예제 #21
0
def get_whois(ipaddr):
    obj = IPWhois(ipaddr)
    WhoisInfo = obj.lookup_whois()

    if WhoisInfo is None:
        return 0
    else:
        return WhoisInfo
예제 #22
0
def look_up():
	if request.method == 'POST':
		website=request.form['website']	
		ip = socket.gethostbyname(website)
		obj = IPWhois(ip)
		results = obj.lookup_whois()
		print ("length is",len(results['nets']))
		return render_template('look_up.html',results=results)
예제 #23
0
파일: Sooty.py 프로젝트: optionalg/Sooty
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']))

        now = datetime.now()  # current date and time
        today = now.strftime("%m-%d-%Y")
        if not os.path.exists('output/' + today):
            os.makedirs('output/' + today)
        f = open('output/' + today + '/' + str(ip.split()) + ".txt", "a+")

        f.write("\n ---------------------------------")
        f.write("\n WHO IS REPORT:")
        f.write("\n ---------------------------------\n")
        f.write("\n CIDR:      " + str(w['nets'][0]['cidr']))
        f.write("\n Name:      " + str(w['nets'][0]['name']))
        # print("  Handle:    " + str(w['nets'][0]['handle']))
        f.write("\n Range:     " + str(w['nets'][0]['range']))
        f.write("\n Descr:     " + str(w['nets'][0]['description']))
        f.write("\n Country:   " + str(w['nets'][0]['country']))
        f.write("\n State:     " + str(w['nets'][0]['state']))
        f.write("\n City:      " + str(w['nets'][0]['city']))
        f.write("\n Address:   " + addr)
        f.write("\n Post Code: " + str(w['nets'][0]['postal_code']))
        # print("  Emails:    " + str(w['nets'][0]['emails']))
        f.write("\n Created:   " + str(w['nets'][0]['created']))
        f.write("\n Updated:   " + str(w['nets'][0]['updated']))
        f.close()
        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
예제 #24
0
class Sender:
    def __init__(self, IP):
        super(Sender, self).__init__()
        self.IP = IP
        self.obj = IPWhois(self.IP)
        self.info = self.obj.lookup_whois()

    def AbuseEmails(self):
        if self.info['nets'][0]['emails']:
            return self.info['nets'][0]['emails']
        else:
            return 'N/A'

    def Description(self):
        if self.info['nets'][0]['description']:
            return self.info['nets'][0]['description']
        else:
            return 'N/A'

    def CType(self):
        self.comp_type = 'N/A'
        return self.comp_type

    def Network(self):
        if self.info['asn_cidr']:
            self.network = self.info['asn_cidr']
            return self.network
        else:
            return 'N/A'

    def Customer(self):
        self.is_customer = 'N/A'
        return self.is_customer

    def External(self):
        self.is_external = 'N/A'
        return self.is_external

    def Country(self):
        self.country = self.info['asn_country_code']
        return self.country

    def Name(self):
        self.comp_name = self.info['asn_description']
        return self.comp_name

    def Query(self):
        self.query = """INSERT INTO senders (SenderIP, Network, CompanyName, CompanyType, Country, IsTeliaCustomer, IsExternal, AbuseEmails) VALUES ("{ip}","{network}","{name}","{ctype}","{country}","{cust}","{ext}","{abuse_emails}")""".format(
            ip=self.IP,
            network=self.Network(),
            name=self.Name(),
            ctype=self.CType(),
            country=self.Country(),
            cust=self.Customer(),
            ext=self.External(),
            abuse_emails=self.AbuseEmails())
        return self.query
예제 #25
0
 def whois_info(self): #Abuse Contact from WHOIs
         out=IPWhois(self.ipaddr)
         whoisthere=out.lookup_whois()
         final=json.dumps(whoisthere,indent=4)
         with open ("/var/tmp/whoisthere.json","w") as file:
                 file.write(final)
         print("---------Abuse Contact Information from Whois Database---------")
         print("Abuse Contact:")
         os.system("cat /var/tmp/whoisthere.json | jq -C '.nets[0].emails'")
예제 #26
0
    def __new__(self, ip):
        try:
            obj = IPWhois(ip)
            results = obj.lookup_whois()

            return results

        except Exception as e:
            print("Whois error: ", e)
예제 #27
0
파일: infmagic.py 프로젝트: kussic/infmagic
def ip2CIDR(ipN):
    for ip in ipN:
        try:
            w = IPWhois(ip)
        except:
            pass


#TODO: I need to move to RDAP at some point!
# for i in w.lookup_rdap():
# 	for x in i['cidr'].split(','):
# 		entry_ip = ip  #Original IP address
# 		entry_asn = w.lookup()['asn'] #ASN Value
# 		entry_cidr = x.strip() #CIDR Value
# 		entry_desc = i['description'].replace('\n', ' ').replace('\r', ' ')
#
# 		print_info ("New entry: %s, %s, %s, %s" % (entry_ip, entry_asn, entry_cidr, entry_desc))
        for i in w.lookup_whois()['nets']:
            for x in i['cidr'].split(','):
                entry_ip = ip  #Original IP address
                try:
                    entry_asn = w.lookup_whois()['asn']  #ASN Value
                except:
                    #pass
                    entry_asn = "N/A"
                try:
                    entry_cidr = x.strip()  #CIDR Value
                except:
                    entry_cidr = "N/A"
                try:
                    entry_desc = i['description'].replace('\n', ' ').replace(
                        '\r', ' ')
                except:
                    entry_desc = "N/A"
                print_info("New entry: %s, %s, %s, %s" %
                           (entry_ip, entry_asn, entry_cidr, entry_desc))

                if arguments['--csv']:
                    #print "CSV: %s" % arguments['--csv']
                    with open('./%s' % arguments['--csv'], 'a') as f:
                        writer = csv.writer(f)
                        writer.writerow(
                            [entry_ip, entry_asn, entry_cidr, entry_desc])
                    pass
예제 #28
0
def whois_lookup(ip: str,
                 file_name: str,
                 use_cache=True) -> Generator[None, None, Optional[dict]]:
    """Perform Whois lookup for a given IP
        :ip: Ip to peform whois lookup
        :returns Optional[dict] with whois data
    """
    ip_obj = ipaddress.ip_address(ip)
    if ip_obj.is_private is True:
        print(ip_obj, "is private")
        return

    cached_cidr = check_ip_in_cache(ip_obj)
    if use_cache is True and cached_cidr:
        print(f"Cache HIT! {ip, cached_cidr}")
        return read_whois_cache(cached_cidr)

    print(f"cache miss: {ip}")

    response = None
    try:
        obj = IPWhois(ip)
        response = obj.lookup_whois()
    except ipwhois.exceptions.IPDefinedError:
        return

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

    if cidr is None:
        return

    details = response['nets'][0]
    name = details['name']
    city = details['city']
    state = details['state']
    country = details['country']
    address = details['address']
    description = details['description']

    cidrs = cidr.split(", ")
    print(f"cidrs: {cidrs}")
    for cidr in cidrs:
        whois_data = {
            'cidr': cidr,
            'name': name,
            'city': city,
            'state': state,
            'country': country,
            'address': address,
            'description': description
        }

        update_whois_cache(cidr, file_name, whois_data)
        yield whois_data
예제 #29
0
def available_mirrors_view(filebucket_id):
    initSession()

    if session['logged_in'] or (request.remote_addr == "127.0.0.1"
                                and can_login_local_without_auth()):
        splitted_ids = filebucket_id.split("_")
        ownstorj_mirrors = OwnStorjMirrors(bucket_id=splitted_ids[0],
                                           file_id=splitted_ids[1])
        mirrors_data = ownstorj_mirrors.get_mirrors_array()
        mirrors_data, mirrors_data_2 = itertools.tee(mirrors_data)
        mirrors_data_2, temp = itertools.tee(mirrors_data_2)

        recent_shard_hash = ""
        current_shard_hash = ""
        available_mirrors_shards_count = 0
        available_mirrors_total_nodes_count = 0
        table_break_positions = []
        country_codes_array = {}
        i = 0

        for file_mirror in temp:
            for mirror in file_mirror.available:
                i += 1
                if mirror['shardHash'] != current_shard_hash:
                    if i != 1:
                        table_break_positions.append(i - 1)
                if mirror['shardHash'] != recent_shard_hash:
                    current_shard_hash = mirror['shardHash']
                    available_mirrors_shards_count += 1

                try:
                    # t1 = Thread(target=whois_lookup_country, args=(mirror['contact']['address']))
                    IP_addr = socket.gethostbyname(
                        str(mirror['contact']['address']))
                    obj = IPWhois(IP_addr)
                    res = obj.lookup_whois()
                    country = res["nets"][0]['country']
                    available_mirrors_total_nodes_count += 1
                    country_codes_array[mirror['contact']['address']] = country
                except BaseException as e:
                    print e

                recent_shard_hash = mirror['shardHash']
        print i

        return render_template(
            'available_mirrors_data.html',
            table_break_positions=table_break_positions,
            available_mirrors_shards_count=available_mirrors_shards_count,
            mirrors_data=mirrors_data,
            mirrors_data_2=mirrors_data_2,
            available_mirrors_total_nodes_count=
            available_mirrors_total_nodes_count,
            country_codes_array=country_codes_array)
    else:
        return make_response(redirect("/login"))
예제 #30
0
def pull_ipwhois_legacy_whois(target):
    eye = IPWhois(target)
    who_is = json.dumps(eye.lookup_whois(get_asn_description=True,
                                         inc_nir=True),
                        indent=4)
    results = json.dumps(eye.lookup_rdap(depth=1), indent=4)
    save_output(str(target), who_is)
    save_output(str(target), results)
    print(f'{results}')
    print(f'{who_is}')
예제 #31
0
def ip_abuse(ip_address):
    obj = IPWhois(ip_address)
    results = obj.lookup_whois(inc_raw=True)

    return {
        "value": ip_address,
        "names": _get_names(ip_address, results),
        "abuse": _get_abuse_emails(results['raw']),
        "raw": results['raw']
    }
예제 #32
0
 def queryIPs(self, data):
     resultsList = []
     for item in tqdm(data):
         try:
             obj = IPWhois(item)
             results = obj.lookup_whois()
             resultsList.append(results)
         except:
             print("error looking up:", item)
     return resultsList.copy()
def sitebilgilerinibul(site):
    ip     = socket.gethostbyname(site)
    obje   = IPWhois(ip)
    obj    = obje.lookup_whois()
    eposta = obj["nets"][0]['emails']
    desc  = obj["nets"][0]['description']
    print  "Site\t: ", site, "\n"
    print "IP adresi\t: ", ip
    print  "\nAçıklama\t: ", desc
    print "\nEmails\t: \n"
    print  email
예제 #34
0
def lookup(ip, rdap=False):
    obj = IPWhois(ip)
    if rdap:
        # TODO: RDAP output includes less relevant info, needs a dedicated formatter
        return obj.lookup_rdap()
    else:
        ret = obj.lookup_whois()
        # remove some fields that clutter
        for x in ['raw', 'raw_referral', 'referral']:
            ret.pop(x, None)
        return ret
예제 #35
0
    def add_kvstore(self,ips_fin):
        
        i=0
        new_ip=""
        dict_yield_new=[]

        #Ignore Splunk certificate warnings
        requests.packages.urllib3.disable_warnings()

        count =len(ips_fin)-1

        for ip in range(0,count):

            #if its contains CIDR, convert it to an IP address and call WHOIS database

            if (str(ips_fin.keys()[i])).find("/") != -1:

                cidr_string = str(ips_fin.keys()[i])
                new_ip = cidr_string.split("/")[0]

                obj = IPWhois(new_ip)
                results1 = obj.lookup_whois()
                
                kv_data = json.dumps(results1)
                r = requests.post(self.kvURI, kv_data, auth=(self.splunkUser, self.splunkPwd), verify=False, headers=self.headers)
                dict_yield_new.append(results1)
                

            #IF NOT CIDR then call WHOIS
            else:
                

                old_ip=str(ips_fin.keys()[i])
                obj = IPWhois(old_ip)
                results2 = obj.lookup_whois()
                kv_data = json.dumps(results2)
                r = requests.post(self.kvURI, kv_data, auth=(self.splunkUser, self.splunkPwd), verify=False, headers=self.headers)
                dict_yield_new.append(results2)
                #print results2

        return dict_yield_new
예제 #36
0
 def extract_whois(self, ip): # extract whois description
     try:
         if re.match(r'^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', ip): # only IPs
             w = IPWhois(ip, timeout=5) # timeout 5
             res = w.lookup_whois(retry_count=2) # legacy whois / retries 2
             descr = res["nets"][0]['description']
             if self.options.verbose:
                 print"[Verbose] - Resolving:", ip
         else:
             descr = None
     except:
         descr = None
     return descr
예제 #37
0
    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)
예제 #38
0
    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
예제 #39
0
파일: netname.py 프로젝트: quangns/test
def analysis(ip):
    target = open("netname.txt", 'a')
    obj = IPWhois(ip.network)
    res = obj.lookup_whois()
    result = res['nets'][0]
    # kiem tra inetnum co trong ban ghi khong
    if 'range' in result:
        if check(result['range']):
            if "\n" in result['description']:
                description_ = result['description'].split('\n')
                target.write("description:  %s %s\n" % (description_[0], description_[-1]))
            else:
                target.write("description:  %s\n" % (result['description']))
            target.write("inetnum:      %s\n" % (result['range']))
            target.write("netname:      %s\n" % (result['name']))
            target.write("cidr:         %s\n" % (result['cidr']))
            target.write("------------------------------------------"
                         "----------------------------------------\n")
            return result['cidr'].split('/')[-1]
    target.close()
예제 #40
0
 def who(self, ip):
     try:
         obj = IPWhois(ip)
         results = obj.lookup_whois()
         if 'nets' in results:
             name=desc=cidr=iprange=''
             if 'name' in results['nets'][0]:
                 name = results['nets'][0]['name']
             if 'description' in results['nets'][0]:
                 desc = results['nets'][0]['description']
                 if desc:
                     desc = desc.replace("\n",",")    
             if 'cidr' in results['nets'][0]:
                 cidr = results['nets'][0]['cidr']
             if 'range' in results['nets'][0]:
                 iprange = results['nets'][0]['range']
                 d = {'Name': name, 'Description': desc, 'CIDR': cidr, 'IPRange': iprange}
             self._add_result('Whois Info:', ip, d)
             
     except Exception as e:
         self._error("Error getting WHOIS report from X-Force Exchange: {0}".format(str(e)))
예제 #41
0
class IPWhoisCLI:
    """
    The CLI wrapper class for outputting formatted IPWhois results.

    Args:
        addr: An IPv4 or IPv6 address as a string, integer, IPv4Address, or
            IPv6Address.
        timeout: The default timeout for socket connections in seconds.
        proxy_http: The urllib.request.ProxyHandler dictionary for proxy
            HTTP support or None.
        proxy_https: The urllib.request.ProxyHandler dictionary for proxy
            HTTPS support or None.
        allow_permutations: allow net.Net() to use additional methods if DNS
            lookups to Cymru fail.
    """

    def __init__(
        self,
        addr,
        timeout,
        proxy_http,
        proxy_https,
        allow_permutations
    ):

        self.addr = addr
        self.timeout = timeout

        handler_dict = None
        if proxy_http is not None:

            handler_dict = {'http': proxy_http}

        if proxy_https is not None:

            if handler_dict is None:

                handler_dict = {'https': proxy_https}

            else:

                handler_dict['https'] = proxy_https

        if handler_dict is None:

            self.opener = None
        else:

            handler = ProxyHandler(handler_dict)
            self.opener = build_opener(handler)

        self.allow_permutations = allow_permutations

        self.obj = IPWhois(address=self.addr,
                           timeout=self.timeout,
                           proxy_opener=self.opener,
                           allow_permutations=self.allow_permutations)

    def generate_output_header(self, query_type='RDAP'):
        """
        The function for generating the CLI output header.

        Args:
            query_type: The IPWhois query type.

        Returns:
            String: The generated output string.
        """

        output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format(
            ANSI['ul'],
            ANSI['b'],
            query_type,
            self.obj.address_str,
            ANSI['end']
        )

        return output

    def generate_output_newline(self, line='0', colorize=True):
        """
        The function for generating a CLI output new line.

        Args:
            line: The line number (0-4). Determines indentation.
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        return generate_output(
            line=line,
            is_parent=True,
            colorize=colorize
        )

    def generate_output_asn(self, json_data=None, hr=True, show_name=False,
                            colorize=True):
        """
        The function for generating CLI output ASN results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        # Python 2.6 doesn't support set literal expressions, use explicit
        # set() instead.
        keys = set(['asn', 'asn_cidr', 'asn_country_code', 'asn_date',
                    'asn_registry']).intersection(json_data)

        output = ''

        for key in keys:

            output += generate_output(
                line='0',
                short=HR_ASN[key]['_short'] if hr else key,
                name=HR_ASN[key]['_name'] if (hr and show_name) else None,
                value=(json_data[key] if (
                    json_data[key] is not None and
                    len(json_data[key]) > 0 and
                    json_data[key] != 'NA') else 'None'),
                colorize=colorize
            )

        return output

    def generate_output_entities(self, json_data=None, hr=True,
                                 show_name=False, colorize=True):
        """
        The function for generating CLI output RDAP entity results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        output = ''
        short = HR_RDAP['entities']['_short'] if hr else 'entities'
        name = HR_RDAP['entities']['_name'] if (hr and show_name) else None

        output += generate_output(
            line='0',
            short=short,
            name=name,
            is_parent=False if (json_data is None or
                                json_data['entities'] is None) else True,
            value='None' if (json_data is None or
                             json_data['entities'] is None) else None,
            colorize=colorize
        )

        if json_data is not None:

            for ent in json_data['entities']:

                output += generate_output(
                    line='1',
                    value=ent,
                    colorize=colorize
                )

        return output

    def generate_output_events(self, source, key, val, line='2', hr=True,
                               show_name=False, colorize=True):
        """
        The function for generating CLI output RDAP events results.

        Args:
            source: The parent key (network or objects).
            key: The event key (events or events_actor).
            val: The event dictionary.
            line: The line number (0-4). Determines indentation.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        output = generate_output(
            line=line,
            short=HR_RDAP[source][key]['_short'] if hr else key,
            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
            is_parent=False if (val is None or
                                len(val) == 0) else True,
            value='None' if (val is None or
                             len(val) == 0) else None,
            colorize=colorize
        )

        if val is not None:

            count = 0
            for item in val:

                try:
                    action = item['action']
                except KeyError:
                    action = None

                try:
                    timestamp = item['timestamp']
                except KeyError:
                    timestamp = None

                try:
                    actor = item['actor']
                except KeyError:
                    actor = None

                if count > 0:
                    output += generate_output(
                        line=str(int(line)+1),
                        is_parent=True,
                        colorize=colorize
                    )

                output += generate_output(
                    line=str(int(line)+1),
                    short=HR_RDAP_COMMON[key]['action'][
                        '_short'] if hr else 'action',
                    name=HR_RDAP_COMMON[key]['action'][
                        '_name'] if (hr and show_name) else None,
                    value=action,
                    colorize=colorize
                )

                output += generate_output(
                    line=str(int(line)+1),
                    short=HR_RDAP_COMMON[key]['timestamp'][
                        '_short'] if hr else 'timestamp',
                    name=HR_RDAP_COMMON[key]['timestamp'][
                        '_name'] if (hr and show_name) else None,
                    value=timestamp,
                    colorize=colorize
                )

                output += generate_output(
                    line=str(int(line)+1),
                    short=HR_RDAP_COMMON[key]['actor'][
                        '_short'] if hr else 'actor',
                    name=HR_RDAP_COMMON[key]['actor'][
                        '_name'] if (hr and show_name) else None,
                    value=actor,
                    colorize=colorize
                )

                count += 1

        return output

    def generate_output_list(self, source, key, val, line='2', hr=True,
                             show_name=False, colorize=True):
        """
        The function for generating CLI output RDAP list results.

        Args:
            source: The parent key (network or objects).
            key: The event key (events or events_actor).
            val: The event dictionary.
            line: The line number (0-4). Determines indentation.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        output = generate_output(
            line=line,
            short=HR_RDAP[source][key]['_short'] if hr else key,
            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
            is_parent=False if (val is None or
                                len(val) == 0) else True,
            value='None' if (val is None or
                             len(val) == 0) else None,
            colorize=colorize
        )

        if val is not None:
            for item in val:
                output += generate_output(
                    line=str(int(line)+1),
                    value=item,
                    colorize=colorize
                )

        return output

    def generate_output_notices(self, source, key, val, line='1', hr=True,
                                show_name=False, colorize=True):
        """
        The function for generating CLI output RDAP notices results.

        Args:
            source: The parent key (network or objects).
            key: The event key (events or events_actor).
            val: The event dictionary.
            line: The line number (0-4). Determines indentation.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        output = generate_output(
            line=line,
            short=HR_RDAP[source][key]['_short'] if hr else key,
            name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
            is_parent=False if (val is None or
                                len(val) == 0) else True,
            value='None' if (val is None or
                             len(val) == 0) else None,
            colorize=colorize
        )

        if val is not None:

            count = 0
            for item in val:

                title = item['title']
                description = item['description']
                links = item['links']

                if count > 0:
                    output += generate_output(
                        line=str(int(line)+1),
                        is_parent=True,
                        colorize=colorize
                    )

                output += generate_output(
                    line=str(int(line)+1),
                    short=HR_RDAP_COMMON[key]['title']['_short'] if hr else (
                        'title'),
                    name=HR_RDAP_COMMON[key]['title']['_name'] if (
                        hr and show_name) else None,
                    value=title,
                    colorize=colorize
                )

                output += generate_output(
                    line=str(int(line)+1),
                    short=HR_RDAP_COMMON[key]['description'][
                        '_short'] if hr else 'description',
                    name=HR_RDAP_COMMON[key]['description'][
                        '_name'] if (hr and show_name) else None,
                    value=description.replace(
                        '\n',
                        '\n{0}'.format(generate_output(line='3'))
                    ),
                    colorize=colorize
                )
                output += self.generate_output_list(
                    source=source,
                    key='links',
                    val=links,
                    line=str(int(line)+1),
                    hr=hr,
                    show_name=show_name,
                    colorize=colorize
                )

                count += 1

        return output

    def generate_output_network(self, json_data=None, hr=True, show_name=False,
                                colorize=True):
        """
        The function for generating CLI output RDAP network results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        output = generate_output(
            line='0',
            short=HR_RDAP['network']['_short'] if hr else 'network',
            name=HR_RDAP['network']['_name'] if (hr and show_name) else None,
            is_parent=True,
            colorize=colorize
        )

        for key, val in json_data['network'].items():

            if key in ['links', 'status']:

                output += self.generate_output_list(
                    source='network',
                    key=key,
                    val=val,
                    line='1',
                    hr=hr,
                    show_name=show_name,
                    colorize=colorize
                )

            elif key in ['notices', 'remarks']:

                output += self.generate_output_notices(
                    source='network',
                    key=key,
                    val=val,
                    line='1',
                    hr=hr,
                    show_name=show_name,
                    colorize=colorize
                )

            elif key == 'events':

                output += self.generate_output_events(
                    source='network',
                    key=key,
                    val=val,
                    line='1',
                    hr=hr,
                    show_name=show_name,
                    colorize=colorize
                )

            elif key not in ['raw']:

                output += generate_output(
                    line='1',
                    short=HR_RDAP['network'][key]['_short'] if hr else key,
                    name=HR_RDAP['network'][key]['_name'] if (
                        hr and show_name) else None,
                    value=val,
                    colorize=colorize
                )

        return output

    def generate_output_objects(self, json_data=None, hr=True, show_name=False,
                                colorize=True):
        """
        The function for generating CLI output RDAP object results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        output = generate_output(
            line='0',
            short=HR_RDAP['objects']['_short'] if hr else 'objects',
            name=HR_RDAP['objects']['_name'] if (hr and show_name) else None,
            is_parent=True,
            colorize=colorize
        )

        count = 0
        for obj_name, obj in json_data['objects'].items():
            if count > 0:
                output += self.generate_output_newline(
                    line='1',
                    colorize=colorize
                )
            count += 1

            output += generate_output(
                line='1',
                short=obj_name,
                is_parent=True,
                colorize=colorize
            )

            for key, val in obj.items():

                if key in ['links', 'entities', 'roles', 'status']:

                    output += self.generate_output_list(
                        source='objects',
                        key=key,
                        val=val,
                        line='2',
                        hr=hr,
                        show_name=show_name,
                        colorize=colorize
                    )

                elif key in ['notices', 'remarks']:

                    output += self.generate_output_notices(
                        source='objects',
                        key=key,
                        val=val,
                        line='2',
                        hr=hr,
                        show_name=show_name,
                        colorize=colorize
                    )

                elif key == 'events':

                    output += self.generate_output_events(
                        source='objects',
                        key=key,
                        val=val,
                        line='2',
                        hr=hr,
                        show_name=show_name,
                        colorize=colorize
                    )

                elif key == 'contact':

                    output += generate_output(
                        line='2',
                        short=HR_RDAP['objects']['contact'][
                            '_short'] if hr else 'contact',
                        name=HR_RDAP['objects']['contact']['_name'] if (
                            hr and show_name) else None,
                        is_parent=False if (val is None or
                                            len(val) == 0) else True,
                        value='None' if (val is None or
                                         len(val) == 0) else None,
                        colorize=colorize
                    )

                    if val is not None:

                        for k, v in val.items():

                            if k in ['phone', 'address', 'email']:

                                output += generate_output(
                                    line='3',
                                    short=HR_RDAP['objects']['contact'][k][
                                        '_short'] if hr else k,
                                    name=HR_RDAP['objects']['contact'][k][
                                        '_name'] if (
                                        hr and show_name) else None,
                                    is_parent=False if (
                                        val is None or
                                        len(val) == 0
                                    ) else True,
                                    value='None' if (val is None or
                                                     len(val) == 0) else None,
                                    colorize=colorize
                                )

                                if v is not None:
                                    for item in v:
                                        i_type = ', '.join(item['type']) if (
                                            isinstance(item['type'], list)
                                        ) else item['type']

                                        i_type = i_type if (
                                            i_type is not None and
                                            len(i_type) > 0) else ''

                                        i_value = item['value'].replace(
                                            '\n',
                                            '\n{0}'.format(
                                                generate_output(
                                                    line='4',
                                                    is_parent=True,
                                                    colorize=colorize
                                                ).replace('\n', ''))
                                        )

                                        tmp_out = '{0}{1}{2}'.format(
                                            i_type,
                                            ': ' if i_type != '' else '',
                                            i_value
                                        )

                                        output += generate_output(
                                            line='4',
                                            value=tmp_out,
                                            colorize=colorize
                                        )

                            else:

                                output += generate_output(
                                    line='3',
                                    short=HR_RDAP['objects']['contact'][k][
                                        '_short'] if hr else k,
                                    name=HR_RDAP['objects']['contact'][k][
                                        '_name'] if (
                                        hr and show_name) else None,
                                    value=v,
                                    colorize=colorize
                                )

                elif key not in ['raw']:

                    output += generate_output(
                        line='2',
                        short=HR_RDAP['objects'][key]['_short'] if hr else key,
                        name=HR_RDAP['objects'][key]['_name'] if (
                            hr and show_name) else None,
                        value=val,
                        colorize=colorize
                    )

        return output

    def lookup_rdap(self, hr=True, show_name=False, colorize=True, **kwargs):
        """
        The function for wrapping IPWhois.lookup_rdap() and generating
        formatted CLI output.

        Args:
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.
            kwargs: Arguments to pass to IPWhois.lookup_rdap().

        Returns:
            String: The generated output string.
        """

        # Perform the RDAP lookup
        ret = self.obj.lookup_rdap(**kwargs)

        if script_args.json:

            output = json.dumps(ret)

        else:

            # Header
            output = self.generate_output_header(query_type='RDAP')

            # ASN
            output += self.generate_output_asn(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            # Entities
            output += self.generate_output_entities(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            # Network
            output += self.generate_output_network(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            # Objects
            output += self.generate_output_objects(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            if 'nir' in ret:

                # NIR
                output += self.generate_output_nir(
                    json_data=ret, hr=hr, show_name=show_name,
                    colorize=colorize
                )
                output += self.generate_output_newline(colorize=colorize)

        return output

    def generate_output_whois_nets(self, json_data=None, hr=True,
                                   show_name=False, colorize=True):
        """
        The function for generating CLI output Legacy Whois networks results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        output = generate_output(
            line='0',
            short=HR_WHOIS['nets']['_short'] if hr else 'nets',
            name=HR_WHOIS['nets']['_name'] if (hr and show_name) else None,
            is_parent=True,
            colorize=colorize
        )

        count = 0
        for net in json_data['nets']:
            if count > 0:
                output += self.generate_output_newline(
                    line='1',
                    colorize=colorize
                )
            count += 1

            output += generate_output(
                line='1',
                short=net['handle'],
                is_parent=True,
                colorize=colorize
            )

            for key, val in net.items():

                if val and '\n' in val:

                    output += generate_output(
                        line='2',
                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,
                        name=HR_WHOIS['nets'][key]['_name'] if (
                            hr and show_name) else None,
                        is_parent=False if (val is None or
                                            len(val) == 0) else True,
                        value='None' if (val is None or
                                         len(val) == 0) else None,
                        colorize=colorize
                    )

                    for v in val.split('\n'):
                        output += generate_output(
                            line='3',
                            value=v,
                            colorize=colorize
                        )

                else:

                    output += generate_output(
                        line='2',
                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,
                        name=HR_WHOIS['nets'][key]['_name'] if (
                            hr and show_name) else None,
                        value=val,
                        colorize=colorize
                    )

        return output

    def generate_output_whois_referral(self, json_data=None, hr=True,
                                       show_name=False, colorize=True):
        """
        The function for generating CLI output Legacy Whois referral results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        output = generate_output(
            line='0',
            short=HR_WHOIS['referral']['_short'] if hr else 'referral',
            name=HR_WHOIS['referral']['_name'] if (hr and show_name) else None,
            is_parent=False if json_data['referral'] is None else True,
            value='None' if json_data['referral'] is None else None,
            colorize=colorize
        )

        if json_data['referral']:

            for key, val in json_data['referral'].items():

                if val and '\n' in val:

                    output += generate_output(
                        line='1',
                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,
                        name=HR_WHOIS['nets'][key]['_name'] if (
                            hr and show_name) else None,
                        is_parent=False if (val is None or
                                            len(val) == 0) else True,
                        value='None' if (val is None or
                                         len(val) == 0) else None,
                        colorize=colorize
                    )

                    for v in val.split('\n'):
                        output += generate_output(
                            line='2',
                            value=v,
                            colorize=colorize
                        )

                else:

                    output += generate_output(
                        line='1',
                        short=HR_WHOIS['nets'][key]['_short'] if hr else key,
                        name=HR_WHOIS['nets'][key]['_name'] if (
                            hr and show_name) else None,
                        value=val,
                        colorize=colorize
                    )

        return output

    def generate_output_nir(self, json_data=None, hr=True, show_name=False,
                            colorize=True):
        """
        The function for generating CLI output NIR network results.

        Args:
            json_data: The data dictionary to process.
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.

        Returns:
            String: The generated output string.
        """

        if json_data is None:
            json_data = {}

        output = generate_output(
            line='0',
            short=HR_WHOIS_NIR['nets']['_short'] if hr else 'nir_nets',
            name=HR_WHOIS_NIR['nets']['_name'] if (hr and show_name) else None,
            is_parent=True,
            colorize=colorize
        )

        count = 0
        if json_data['nir']:

            for net in json_data['nir']['nets']:

                if count > 0:

                    output += self.generate_output_newline(
                        line='1',
                        colorize=colorize
                    )

                count += 1

                output += generate_output(
                    line='1',
                    short=net['handle'],
                    is_parent=True,
                    colorize=colorize
                )

                for key, val in net.items():

                    if val and (isinstance(val, dict) or '\n' in val or
                                key == 'nameservers'):

                        output += generate_output(
                            line='2',
                            short=(
                                HR_WHOIS_NIR['nets'][key]['_short'] if (
                                    hr) else key
                            ),
                            name=HR_WHOIS_NIR['nets'][key]['_name'] if (
                                hr and show_name) else None,
                            is_parent=False if (val is None or
                                                len(val) == 0) else True,
                            value='None' if (val is None or
                                             len(val) == 0) else None,
                            colorize=colorize
                        )

                        if key == 'contacts':

                            for k, v in val.items():

                                if v:

                                    output += generate_output(
                                        line='3',
                                        is_parent=False if (
                                            len(v) == 0) else True,
                                        name=k,
                                        colorize=colorize
                                    )

                                    for contact_key, contact_val in v.items():

                                        if v is not None:

                                            tmp_out = '{0}{1}{2}'.format(
                                                contact_key,
                                                ': ',
                                                contact_val
                                            )

                                            output += generate_output(
                                                line='4',
                                                value=tmp_out,
                                                colorize=colorize
                                            )
                        elif key == 'nameservers':

                            for v in val:
                                output += generate_output(
                                    line='3',
                                    value=v,
                                    colorize=colorize
                                )
                        else:

                            for v in val.split('\n'):
                                output += generate_output(
                                    line='3',
                                    value=v,
                                    colorize=colorize
                                )

                    else:

                        output += generate_output(
                            line='2',
                            short=(
                                HR_WHOIS_NIR['nets'][key]['_short'] if (
                                    hr) else key
                            ),
                            name=HR_WHOIS_NIR['nets'][key]['_name'] if (
                                hr and show_name) else None,
                            value=val,
                            colorize=colorize
                        )

        else:

            output += 'None'

        return output

    def lookup_whois(self, hr=True, show_name=False, colorize=True, **kwargs):
        """
        The function for wrapping IPWhois.lookup_whois() and generating
        formatted CLI output.

        Args:
            hr: Enable human readable key translations.
            show_name: Show human readable name (default is to only show
                short).
            colorize: Colorize the console output with ANSI colors.
            kwargs: Arguments to pass to IPWhois.lookup_whois().

        Returns:
            String: The generated output string.
        """

        # Perform the RDAP lookup
        ret = self.obj.lookup_whois(**kwargs)

        if script_args.json:

            output = json.dumps(ret)

        else:

            # Header
            output = self.generate_output_header(query_type='Legacy Whois')

            # ASN
            output += self.generate_output_asn(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            # Network
            output += self.generate_output_whois_nets(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            # Referral
            output += self.generate_output_whois_referral(
                json_data=ret, hr=hr, show_name=show_name, colorize=colorize
            )
            output += self.generate_output_newline(colorize=colorize)

            if 'nir' in ret:

                # NIR
                output += self.generate_output_nir(
                    json_data=ret, hr=hr, show_name=show_name,
                    colorize=colorize
                )
                output += self.generate_output_newline(colorize=colorize)

        return output
예제 #42
0
import requests
from ipwhois import IPWhois

r = requests.get('http://ipv4.icanhazip.com')

ip = r.text

ip = ip.rstrip()
obj = IPWhois(ip)
results = obj.lookup_whois()
print "sensorIP="+str(ip)+", ASN="+str(results['asn'])+", ASN_Country="+str(results['asn_country_code'])+", description="+str(results['nets'][0]['description']) + ", network_name="+str(results['nets'][0]['name'])+", network_range="+str(results['nets'][0]['range'])