我如何在Python中进行DNS查询,包括引用/ etc / hosts?
dnspython会很好地完成我的DNS查询,但是完全忽略了/etc/hosts
的内容。
有没有一个Python库的电话会做正确的事情? 即首先在etc/hosts
检查,否则只能退回到DNS查找。
我不确定你是否想自己做DNS查询,或者你只是想要一个主机的IP。 如果你想要后者,
import socket print socket.gethostbyname('localhost') # result from hosts file print socket.gethostbyname('google.com') # your os sends out a dns query
Python中的正常名称parsing工作正常。 为什么你需要DNSpython呢。 只要使用套接字的getaddrinfo
,它遵循为您的操作系统configuration的规则(在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))]
list( map( lambda x: x[4][0], socket.getaddrinfo( \ 'www.example.com.',22,type=socket.SOCK_STREAM)))
为您提供www.example.com的地址列表。 (ipv4和ipv6)
我发现这种方法可以将扩展成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主机名: