如何在Python中进行DNS查找,包括引用/ etc / hosts?

时间:2010-05-10 18:14:43

标签: python dns

dnspython可以非常好地进行DNS查找,但它完全忽略了/etc/hosts的内容。

是否有一个python库调用哪个会做正确的事情?即先在etc/hosts中检查,否则只回退到DNS查找?

7 个答案:

答案 0 :(得分:97)

我不确定您是否想要自己进行DNS查找或者如果您只想要主机的IP。如果你想要后者,

import socket
print(socket.gethostbyname('localhost')) # result from hosts file
print(socket.gethostbyname('google.com')) # your os sends out a dns query

答案 1 :(得分:86)

Python中的普通名称解析工作正常。为什么你需要DNSpython。只需使用遵循为您的操作系统配置的规则的socket getaddrinfo(在Debian上,它遵循/etc/nsswitch.conf

>>> print socket.getaddrinfo('google.com', 80)
[(10, 1, 6, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::63', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::68', 80, 0, 0)), (10, 1, 6, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 2, 17, '', ('2a00:1450:8006::93', 80, 0, 0)), (10, 3, 0, '', ('2a00:1450:8006::93', 80, 0, 0)), (2, 1, 6, '', ('209.85.229.104', 80)), (2, 2, 17, '', ('209.85.229.104', 80)), (2, 3, 0, '', ('209.85.229.104', 80)), (2, 1, 6, '', ('209.85.229.99', 80)), (2, 2, 17, '', ('209.85.229.99', 80)), (2, 3, 0, '', ('209.85.229.99', 80)), (2, 1, 6, '', ('209.85.229.147', 80)), (2, 2, 17, '', ('209.85.229.147', 80)), (2, 3, 0, '', ('209.85.229.147', 80))]

答案 2 :(得分:3)

听起来您不想自己解析 dns(这可能是错误的命名法)dnspython 似乎是一个独立的 dns 客户端,可以理解地忽略您的操作系统,因为它绕过了操作系统的实用程序。

我们可以查看名为 getent 的 shell 实用程序以了解(类似 debian 11)操作系统如何为程序解析 dns,这可能是所有使用套接字实现的类似 *nix 的系统的标准。< /p>

参见 man getent 的“hosts”部分,其中提到了 getaddrinfo 的使用,我们可以将其视为 man getaddrinfo

要在python中使用它,我们必须从数据结构中提取一些信息

.

import socket

def get_ipv4_by_hostname(hostname):
    # see `man getent` `/ hosts `
    # see `man getaddrinfo`

    return list(
        i        # raw socket structure
            [4]  # internet protocol info
            [0]  # address
        for i in 
        socket.getaddrinfo(
            hostname,
            0  # port, required
        )
        if i[0] is socket.AddressFamily.AF_INET  # ipv4

        # ignore duplicate addresses with other socket types
        and i[1] is socket.SocketKind.SOCK_RAW  
    )

print(get_ipv4_by_hostname('localhost'))
print(get_ipv4_by_hostname('google.com'))

答案 3 :(得分:2)

list( map( lambda x: x[4][0], socket.getaddrinfo( \
     'www.example.com.',22,type=socket.SOCK_STREAM)))

为您提供www.example.com的地址列表。 (ipv4和ipv6)

答案 4 :(得分:0)

此代码很好地用于返回可能属于特定URI的所有IP地址。由于许多系统现在处于托管环境(AWS / Akamai / etc)中,因此系统可能会返回多个IP地址。 Lambda是从@Peter Silva借来的。

def get_ips_by_dns_lookup(target, port=None):
    '''
        this function takes the passed target and optional port and does a dns
        lookup. it returns the ips that it finds to the caller.

        :param target:  the URI that you'd like to get the ip address(es) for
        :type target:   string
        :param port:    which port do you want to do the lookup against?
        :type port:     integer
        :returns ips:   all of the discovered ips for the target
        :rtype ips:     list of strings

    '''
    import socket

    if not port:
        port = 443

    return list(map(lambda x: x[4][0], socket.getaddrinfo('{}.'.format(target),port,type=socket.SOCK_STREAM)))

ips = get_ips_by_dns_lookup(target='google.com')

答案 5 :(得分:0)

上面的答案是针对Python 2的。如果您使用的是Python 3,则代码如下。

>>> import socket
>>> print(socket.gethostbyname('google.com'))
8.8.8.8
>>>

答案 6 :(得分:-2)

我发现这种方法可以将扩展为IP列表的DNS RR主机名扩展到成员主机名列表中:

#!/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

当我运行它时,会列出一些1e100.net主机名: