Recently I needed to check if a large number of hostnames were resolving to valid IP addresses on an internal network. This is what I came up with:
for /F %i in (names.txt) do @echo %i & nslookup %i | findstr /n "Address" | findstr /b "5"
The output looks as follows:
TESTBOX1
5:Address: 10.11.20.43
TESTBOX2
5:Address: 10.11.20.44
TESTBOX3
5:Address: 10.11.20.45
TESTBOX4
*** dnsbox1.lab.local can't find TESTBOX4: Non-existent domain
for /F %i in (names.txt) do @echo %i & nslookup %i | findstr /n "Address" | findstr /b "5"
The output looks as follows:
TESTBOX1
5:Address: 10.11.20.43
TESTBOX2
5:Address: 10.11.20.44
TESTBOX3
5:Address: 10.11.20.45
TESTBOX4
*** dnsbox1.lab.local can't find TESTBOX4: Non-existent domain
As we can see first three records resolve. The fourth one doesn't have DNS record.
For this to work, each hostname must be on a separate line in a text file "names.txt" and the command must be run from directory where the file sits. Alternatively you can specify full path (i.e c:\names.txt).
Let's break it down and see what's actually going on.
We use for /f loop to parse names.txt and assign each line to variable %i, we then suppress output (@echo) of nslookup and parse it to output only lines containing word Address (findstr /n), we also prepend a number of the line the matching string was found on. Then we again parse the output to display only lines starting with 5.
This is what we get if we break the command down to separate chunks:
Here we only output file contents.
for /F %i in (names.txt) do @echo %i
TESTBOX1
TESTBOX2
TESTBOX3
TESTBOX4
Here we display full nslookup output:
for /F %i in (names.txt) do @echo %i & nslookup %i
TESTBOX1
Server: dnsbox1.lab.local
Address: 10.11.20.43
TESTBOX2
Server: dnsbox1.lab.local
Address: 10.11.20.44
TESTBOX3
Server: dnsbox1.lab.local
Address: 10.11.20.45
TESTBOX4
Server: dnsbox1.lab.local
*** dnsbox1.lab.local can't find TESTBOX4: Non-existent domain
Here we display full nslookup output with numbered lines:
for /F %i in (names.txt) do @echo %i & nslookup %i | findstr /n "Address"
TESTBOX1
2:Address: 10.10.10.10
5:Address: 10.11.20.43
TESTBOX2
2:Address: 10.10.10.10
5:Address: 10.11.20.44
TESTBOX3
2:Address: 10.10.10.10
5:Address: 10.11.20.45
TESTBOX4
*** dnsbox1.lab.local can't find TESTBOX4: Non-existent domain
2:Address: 10.10.10.10
5:Address: 10.11.20.43
TESTBOX2
2:Address: 10.10.10.10
5:Address: 10.11.20.44
TESTBOX3
2:Address: 10.10.10.10
5:Address: 10.11.20.45
TESTBOX4
*** dnsbox1.lab.local can't find TESTBOX4: Non-existent domain
2:Address: 10.10.10.10
If we want to query specific DNS server (replace [DNSsrv] with correct IP/name)
for /F %i in (names.txt) do @echo %i & nslookup %i [DNSsrv] | findstr /n "Address" | findstr /b "5"
If you want to use it in a batch file you've to specify variables with double percentage sign ("%%i).
Comments
Post a Comment