0

I'm trying to get the NS of a subdomain, but I get a NoAnswer Exception.

I suspect it's because asking for the NS is only working on the root domain, but how can I do then?

Is there a way to achieve it using dnspython or do I have to remove each subpart until the NS work?

Cyril N.
  • 38,875
  • 36
  • 142
  • 243

1 Answers1

0

Here's my answer to my own question. I finally decided to go up the ladder and remove each sub parts of the domain up to the last dot (keeping the last two parts).

Here's the code:

def ns_lookup(domain):
    parts = domain.split('.')
    lookup = resolver.Resolver()
    lookup.timeout = 3

    ns_ips = None
    while len(parts) >= 2:
        try:
            nameservers = [a.to_text() for a in lookup.query('.'.join(parts), 'NS')]
            ns_ips = [resolver.query(ns)[0].to_text() for ns in nameservers]
            if len(ns_ips) > 0:
                return ns_ips
        except exception.Timeout:
            return []
        except (resolver.NoAnswer, resolver.NXDOMAIN, resolver.NoNameservers):
            pass

        parts.pop(0)

    return False

And it works that way:

ns_ips = ns_lookup(domain)
if ns_ips is False:
    return False

if len(ns_ips) == 0:
    return []

lookup = resolver.Resolver(configure=False)
lookup.timeout = 3
lookup.nameservers = ns_ips
lookup.query(domain, 'A')  # The entry you want.

Hope that helps anyone else.

Cyril N.
  • 38,875
  • 36
  • 142
  • 243