如何在 bash 中使用 nslookup 来验证 DNS 是否配置正确?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41060027/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use nslookup in bash to verify is DNS is configured properly?
提问by sorin
Mainly I want to detect if DNS is configured properly on a machine by using nslookup
. Sadly it seems that nslookup still returns success error codes when it fails to lookup an entry. Also the fact that different queries could return multiple results makes it harder to test it.
主要是我想通过使用nslookup
. 遗憾的是,当无法查找条目时,nslookup 似乎仍会返回成功错误代码。此外,不同的查询可能返回多个结果的事实也使得测试变得更加困难。
So I want to write a bash snippet that returns success if the dns entry resolved successfully. I don't care if I get multiple results.
所以我想写一个 bash 片段,如果 dns 条目成功解析,则返回成功。我不在乎我是否得到多个结果。
Example nslookup -type=srv _ldap._tcp.DOMAIN.COM
例子 nslookup -type=srv _ldap._tcp.DOMAIN.COM
回答by Isaac
The correct solution would be to use dig and test if there is any text with the short option:
正确的解决方案是使用 dig 并测试是否有任何带有短选项的文本:
[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"
回答by Inian
Agree the fact, nslookup
, returns 0
for both successful and failing DNS look-ups. You can achieve what you are trying to do, but post-processing the output of the command.
同意事实,成功和失败的 DNS 查找都会nslookup
返回0
。您可以实现您想要做的事情,但对命令的输出进行后处理。
You can put up a dnsLookup.sh
script with something like
你可以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"
Running for some sample URL's
运行一些示例 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
回答by sorin
The trick is to use host | grep
commands instead of nslookup
because this one is less verbose, making it much easier to parse with grep.
诀窍是使用host | grep
命令而不是nslookup
因为这个命令不那么冗长,使用 grep 更容易解析。
Here is a command that fails if the DNS resolution fails:
如果 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
}
Note: As you can see my example it specific to SRV
queries but you can easily adapt change the parameter and the grep filter to make it work with others.
注意:如您所见,我的示例特定于SRV
查询,但您可以轻松调整参数和 grep 过滤器以使其与其他人一起使用。