How can I do DNS lookups in Python, including referring to /etc/hosts?

前端 未结 6 1254
醉梦人生
醉梦人生 2020-11-27 14:51

dnspython will do my DNS lookups very nicely, but it entirely ignores the contents of /etc/hosts.

Is there a python library call which will do the right

6条回答
  •  一个人的身影
    2020-11-27 15:18

    I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

    #!/usr/bin/python
    
    def expand_dnsname(dnsname):
        from socket import getaddrinfo
        from dns import reversename, resolver
        namelist = [ ]
        # expand hostname into dict of ip addresses
        iplist = dict()
        for answer in getaddrinfo(dnsname, 80):
            ipa = str(answer[4][0])
            iplist[ipa] = 0
        # run through the list of IP addresses to get hostnames
        for ipaddr in sorted(iplist):
            rev_name = reversename.from_address(ipaddr)
            # run through all the hostnames returned, ignoring the dnsname
            for answer in resolver.query(rev_name, "PTR"):
                name = str(answer)
                if name != dnsname:
                    # add it to the list of answers
                    namelist.append(name)
                    break
        # if no other choice, return the dnsname
        if len(namelist) == 0:
            namelist.append(dnsname)
        # return the sorted namelist
        namelist = sorted(namelist)
        return namelist
    
    namelist = expand_dnsname('google.com.')
    for name in namelist:
        print name
    

    Which, when I run it, lists a few 1e100.net hostnames:

提交回复
热议问题