我主要想通过使用nslookup来检测是否在机器上正确配置了DNS。遗憾的是,当nslookup查找条目失败时,它似乎仍然返回成功错误代码。此外,不同的查询可能会返回多个结果,这也使得测试变得更加困难。
因此,我想编写一个bash代码片段,如果dns条目解析成功,该代码段将返回成功。我不关心我是否得到了多个结果。
示例nslookup -type=srv _ldap._tcp.DOMAIN.COM
发布于 2016-12-10 00:53:34
正确的解决方案应该是使用dig并测试是否有任何带有short选项的文本:
[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"发布于 2016-12-09 20:44:30
同意这一事实,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发布于 2016-12-09 22:14:05
诀窍是使用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过滤器,使其与其他查询一起工作。
https://stackoverflow.com/questions/41060027
复制相似问题