如何在 bash 中使用 nslookup 来验证 DNS 配置是否正确?



主要是我想通过使用nslookup来检测DNS是否在计算机上正确配置。可悲的是,nslookup在查找条目失败时似乎仍然返回成功错误代码。此外,不同的查询可能返回多个结果这一事实使得测试它变得更加困难。

所以我想写一个 bash 片段,如果 dns 条目解析成功,它会返回成功。我不在乎我是否得到多个结果。

示例nslookup -type=srv _ldap._tcp.DOMAIN.COM

正确的解决方案是使用 dig 并测试是否有任何带有 short 选项的文本:

[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"

同意这一事实,nslookup,为成功和失败的 DNS 查找返回0。您可以实现您尝试执行的操作,但对命令的输出进行后处理。

你可以放一个dnsLookup.sh脚本,上面有类似的东西

#!/bin/bash
# Checking for the resolved IP address from the end of the command output. Refer
# the normal command output of nslookup to understand why.
resolvedIP=$(nslookup "$1" | awk -F':' '/^Address: / { matched = 1 } matched { print $2}' | xargs)
# Deciding the lookup status by checking the variable has a valid IP string
[[ -z "$resolvedIP" ]] && echo "$1" lookup failure || echo "$1" resolved to "$resolvedIP"

运行一些示例 URL

dudeOnMac:~$ ./dnsLookup.sh www.google.com
www.google.com resolved to 206.78.111.12
dudeOnMac:~$ ./dnsLookup.sh www.googlejunkaddress.com
www.googlejunkaddress.com lookup failure

诀窍是使用host | grep命令而不是nslookup因为这个命令不那么冗长,这使得使用 grep 解析要容易得多。

下面是一个在 DNS 解析失败时失败的命令:

host -t srv _ldap._tcp.EXAMPLE.COM | grep "has SRV record" >/dev/null ||     {
echo "FATAL: Unable to locate ldap servers, probably you are not on intranet or your DNS servers are broken."
exit 2
}

注意:正如您所看到的,我的示例特定于SRV查询,但您可以轻松地调整更改参数和 grep 过滤器以使其与其他查询一起使用。

最新更新