Skip to content

Instantly share code, notes, and snippets.

@meramsey
Last active August 13, 2021 12:55
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save meramsey/69a55c595d53150bf781189c51e92518 to your computer and use it in GitHub Desktop.
Save meramsey/69a55c595d53150bf781189c51e92518 to your computer and use it in GitHub Desktop.
Aync Lookup a list of domains IP and ASN Description from a csv
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment