如何使用 bash 中的 nslookup 来验证 DNS 是否配置正确?
How to use nslookup in bash to verify is DNS is configured properly?
主要是想通过nslookup
检测机器上的DNS配置是否正确。遗憾的是,当 nslookup 无法查找条目时,它似乎仍然 returns 成功错误代码。此外,不同的查询可能 return 多个结果这一事实使得测试变得更加困难。
所以我想写一个 bash 片段,如果 dns 条目成功解析,return 就会成功。我不在乎我是否得到多个结果。
示例nslookup -type=srv _ldap._tcp.DOMAIN.COM
同意这个事实,nslookup
、returns 0
成功和失败的 DNS 查找。您可以实现您想要做的事情,但是 post- 处理命令的输出。
您可以创建一个 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 "" | awk -F':' '/^Address: / { matched = 1 } matched { print }' | xargs)
# Deciding the lookup status by checking the variable has a valid IP string
[[ -z "$resolvedIP" ]] && echo "" lookup failure || echo "" 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 过滤器以使其与其他人一起使用。
正确的解决方案是使用 dig 并测试是否有带有 short 选项的文本:
[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"
主要是想通过nslookup
检测机器上的DNS配置是否正确。遗憾的是,当 nslookup 无法查找条目时,它似乎仍然 returns 成功错误代码。此外,不同的查询可能 return 多个结果这一事实使得测试变得更加困难。
所以我想写一个 bash 片段,如果 dns 条目成功解析,return 就会成功。我不在乎我是否得到多个结果。
示例nslookup -type=srv _ldap._tcp.DOMAIN.COM
同意这个事实,nslookup
、returns 0
成功和失败的 DNS 查找。您可以实现您想要做的事情,但是 post- 处理命令的输出。
您可以创建一个 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 "" | awk -F':' '/^Address: / { matched = 1 } matched { print }' | xargs)
# Deciding the lookup status by checking the variable has a valid IP string
[[ -z "$resolvedIP" ]] && echo "" lookup failure || echo "" 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 过滤器以使其与其他人一起使用。
正确的解决方案是使用 dig 并测试是否有带有 short 选项的文本:
[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"