6

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

sorin
  • 161,544
  • 178
  • 535
  • 806

3 Answers3

18

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"
  • Thanks! Mine works too but I have to confess that yours is better shorter and easier to read. – sorin Dec 09 '16 at 19:32
  • 1
    I think this will also give positive results for timeouts. What if the output is: `;; connection timed out; no servers could be reached` ? – Zeeshan Dec 12 '22 at 03:21
5

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
Inian
  • 80,270
  • 14
  • 142
  • 161
4

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.

sorin
  • 161,544
  • 178
  • 535
  • 806
  • Not always fail: `host -t srv _ldap._tcp.EXAMPLE.COM.; echo $? _ldap._tcp.EXAMPLE.COM has no SRV record 0`. –  Dec 09 '16 at 16:33
  • Take a look at my full command, it pipes the output to grep and grep does return an error code if it does fail to do a match. So this line will succeed only if the output of host command contains `has SRV record`, which was exactly what I was looking for. – sorin Dec 09 '16 at 16:37