问题
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.
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.
Example nslookup -type=srv _ldap._tcp.DOMAIN.COM
回答1:
The correct solution would be to use dig and test if there is any text with the short option:
[ "$(dig +short -t srv _ldap._tcp.example.com.)" ] && echo "got answer"
回答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
回答3:
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.
Here is a command that fails if the DNS resolution fails:
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.
来源:https://stackoverflow.com/questions/41060027/how-to-use-nslookup-in-bash-to-verify-is-dns-is-configured-properly