为什么当nslookup尝试解析地址时,我的/etc/hosts文件没有被查询?

我在我的/etc/hosts文件中解析了几个本地域名到127.0.0.1。一段时间以来一切都很正常,但现在当我运行:
nslookup test.local

导致的结果是:
Server:     192.168.1.3
Address:    192.168.1.3#53

** server can't find test.local: NXDOMAIN

192.168.1.3 是我们的网络 DNS,它不应该知道我的本地域名 test.local。经过几次搜索,我发现 /etc/nsswitch.conf 文件保存了查询 DNS 源的优先级信息。但是那里没有问题!这是我的配置:

# /etc/nsswitch.conf
#
# Example configuration of GNU Name Service Switch functionality.
# If you have the `glibc-doc-reference' and `info' packages installed, try:
# `info libc "Name Service Switch"' for information about this file.

passwd:         compat
group:          compat
shadow:         compat

hosts:          files mdns4_minimal [NOTFOUND=return] dns
networks:       files

protocols:      db files
services:       db files
ethers:         db files
rpc:            db files

netgroup:       nis

有人知道为什么我的hosts文件没有包含在DNS查找中吗?
3个回答

nslookup只执行适当的 DNS 解析,这与您的其他应用程序使用的Name Service Switch子系统明显不同;也就是说,nslookup忽略了/etc/hosts和mDNS。

要测试本地解析,可以使用使用NSS的某个工具。例如,使用ping <hostname>。以下是基于我的网络上的/etc/hosts条目的简单演示。

$ nslookup bert
Server:     8.8.8.8
Address:    8.8.8.8#53

** server can't find bert: NXDOMAIN

$ ping bert
PING bert (10.10.0.4) 56(84) bytes of data.
64 bytes from bert (10.10.0.4): icmp_seq=1 ttl=64 time=0.352 ms
64 bytes from bert (10.10.0.4): icmp_seq=2 ttl=64 time=0.407 ms

请注意,有些 DNS 服务器和代理可以考虑到 /etc/hosts 文件。在这些情况下,nslookup 可能会返回来自本地源的结果。

8应该使用 getent ahosts 而不是 ping,因为前者不需要 ping 那样的额外信息。 - Mikko Rantalainen
使用getent多年来获取用户和组信息,我从未想到它还可以处理DNS。 - colm.anseo
为什么你说nslookup忽略了/etc/hosts?当我在IP地址上运行nslookup时,它会给我一些只存在于我的/etc/hosts中的条目。事实上,我正在尝试弄清楚如何让nslookup忽略/etc/hosts。 - lord_nimon

我猜你想要从/etc/hosts文件中解析特定主机(mysite.com)的名称。
另一个可能导致这种行为的常见问题是,你可能在/etc/hosts文件中有多个相同IP的条目,例如:
1.1.1.1 host1.domain1.com
1.1.1.1 host2.domain2.com

在某些实现中,这可能会导致名称解析被传递给DNS。一个快速的解决方法是将所有内容分组到一行中。
1.1.1.1 host1.domain1.com host2.domain2.com

另一个我经常看到的常见情况是有人(通常是我)在/etc/hosts文件中将IP地址与主机名颠倒 - 例如:
mysite.com    10.2.3.4

乍一看,它看起来很正常... 这是我解决问题的方法,大约有50%的成功率:
10.2.3.4    mysite.com

这次真的有罪了...#叹息 - CybeX
1通常,hosts文件会预先定义127.0.0.1 localhost的条目。做错了就是非常错误的事情 :-) - m3nda