Resovle DnsName With Python

2023-08-17

筆記如何使用 Python 批次查詢 DNS 紀錄 😃

logo

說明

目前使用上的限制:

  • 只能在特定的 name server 下進行搜尋。
  • 無法查詢 CNMAE 並接續查詢為 A
import dns.resolver

resolver = dns.resolver.Resolver()

def resolve_dns_name(hostname, server='8.8.8.8):
    resolver = dns.resolver.Resolver()
    resolver.nameservers = [server]
    try:
        answers = resolver.resolve(hostname, 'A')
        res = []
        for answer in answers:
            res.append(answer.address)
        
        return res
    except:
        # try:
        #     cname_answers = resolver.resolve(hostname, 'CNAME')
        #     cname_res = []
        #     for cname_answer in cname_answers:
        #         cname_res.extend(resolve_dns_name(str(cname_answer.target).strip('.')))
            
        #     return cname_res
        # except dns.exception.DNSException as e:
        #   return []
        return []

res = {}

if __name__ == "__main__":
    for record in ['a.foo', 'b.bar', 'c.baz']:
        res[record] = {
            'hostname' : record,
            'ip' : ', '.join(resolve_dns_name(record))
        }

        print(f'{res[record]["hostname"]};{res[record]["ip"]}')