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

时间:2016-12-09 12:00:36

标签: bash nslookup

主要是我想使用nslookup检测是否在计算机上正确配置了DNS。遗憾的是,当nslookup无法查找条目时,它仍然会返回成功错误代码。此外,不同的查询可能会返回多个结果,这使得测试更加困难。

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

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

3 个答案:

答案 0 :(得分:7)

正确的解决方案是使用挖掘和测试是否有任何带有短选项的文本:

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

答案 1 :(得分:2)

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.

You can put up a dnsLookup.sh script with something like

#!/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"

Running for some sample URL's

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

答案 2 :(得分:1)

诀窍是使用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过滤器以使其与其他人一起使用。