Only needs two external libraries
https://github.com/saghul/aiodns
https://github.com/secynic/ipwhois
pip install aiodns ipwhoisChange paths to source and destination csv.
Run the script via python
python lookupdomainsipandasn.pyOnly needs two external libraries
https://github.com/saghul/aiodns
https://github.com/secynic/ipwhois
pip install aiodns ipwhoisChange paths to source and destination csv.
Run the script via python
python lookupdomainsipandasn.py| import aiodns | |
| import asyncio | |
| import csv | |
| import os | |
| from ipwhois import IPWhois | |
| loop = asyncio.get_event_loop() | |
| resolver = aiodns.DNSResolver(loop=loop) | |
| csvFilePath = os.path.expanduser('~/domains_to_lookup.csv') | |
| async def query(name, query_type): | |
| return await resolver.query(name, query_type) | |
| with open(csvFilePath, mode='r') as infile: | |
| reader = csv.reader(infile) | |
| domains_dict = {rows[0]: rows[1] for rows in reader} | |
| # print(domains_dict) | |
| def get_a_record(name): | |
| """Get A record(IPv4 address) for the name provided. | |
| :param name: Hostname to find A record/IP for. | |
| :type name: str | |
| :return: Returns an A record also known as an IPv4 address otherwise `None` | |
| :rtype: str | |
| :Example: | |
| >>> print(get_a_record("google.com")) | |
| 172.217.15.206 | |
| """ | |
| try: | |
| coro = query(str(name).lower(), 'A') | |
| result = loop.run_until_complete(coro) | |
| ip = str(result[0].host) | |
| except: | |
| ip = None | |
| return ip | |
| def get_asn_description(ipv4): | |
| """Get ASN description for IPv4 address provided. | |
| :param ipv4: IPv4 address to find ASN description for. | |
| :type ipv4: str | |
| :return: Returns ASN description for IPv4 address provided otherwise `None` | |
| :rtype: str | |
| :Example: | |
| >>> print(get_asn_description("104.26.7.186")) | |
| CLOUDFLARENET, US | |
| """ | |
| try: | |
| obj = IPWhois(ipv4) | |
| results = obj.lookup_whois() | |
| asn = str(results['asn_description']) | |
| except: | |
| asn = None | |
| return asn | |
| # field names | |
| fields = ['Domain', 'IPv4', 'ASN Description'] | |
| csv_file = open(os.path.expanduser('~/ip_asn_domain_lookups.csv'), 'w') | |
| csv_writer = csv.writer(csv_file, delimiter=",") | |
| for domain in domains_dict.keys(): | |
| ipv4 = get_a_record(domain) | |
| if ipv4 is not None: | |
| asn = get_asn_description(ipv4) | |
| else: | |
| asn = 'Unknown' | |
| row = [domain, ipv4, asn] | |
| print(row) | |
| csv_writer.writerow(row) | |
| csv_file.close() |