Resolve 750 Domains in One Line

Let’s say, just for example, that you have a (*NIX-formatted) text file filled with 750 domain names and you want to resolve them all to IP addresses. Let’s also assume that you’re using Windows XP and you have access to Cygwin but that’s about it. Cygwin apparently doesn’t have dig yet, so you’re forced to use nslookup. What do you do?

First, let’s take a look at the output of nslookup when you resolve a single domain.

$ nslookup www.slashdot.org
Non-authoritative answer:
Server:  dnsr1.sbcglobal.net
Address:  68.94.156.1

Name:    www.slashdot.org
Address:  66.35.250.151  

Okay, that’s a multi-line answer. Looking through the man page, I couldn’t find a way to limit the output to the IP address, so we’ll have to use bash trickery to make it happen. You’re smart people, here’s my solution with absolutely no ado.

nslookup www.slashdot.org 2>&1 | grep Address | tail -1 | awk '{print $2}'  

I had to use the 2>&1 piece because (apparently) the “Non-authoritative answer:” portion of the output is printed to STDERR. Why? Who knows. Using 2>&1 gloms the STDERR output onto STDOUT so it can be filtered out by the following grep. Then, tail -1 to get the last “Address” line printed, and then awk to print the address rather than the heading.

But wait, there’s trouble! Try Google:

$ nslookup www.google.com
Non-authoritative answer:
Server:  dnsr1.sbcglobal.net
Address:  68.94.156.1

Name:    www.l.google.com
Addresses:  64.233.161.147, 64.233.161.99, 64.233.161.103, 64.233.161.104
Aliases:  www.google.com  

Our grep statement will still catch the “Addresses” line, but now the IPs have commas between them, which awk will include in its output (because it’s tokenized by spaces), so we’ll have to do away with the commas.

nslookup www.slashdot.org 2>&1 | grep Address | tail -1 | tr ',' ' ' | awk '{print $2}'  

The new tr command will translate commas into spaces, allowing awk to properly snag the IP. This gives us a single command that will take in a domain name and output an IP address (provided that nslookup succeeds). How do we feed it an entire text file? Let’s presume that our file is called domains.txt.

for i in `cat domains.txt`
    do nslookup $i 2>&1 | grep Address | tail -1 | tr ',' ' ' | awk '{print $2}'
done  

If you were running this on the command line rather than in a script, you’d want to put semicolons between the lines (or hit \ to continue input on the next line). Provided that the input file is formatted as *NIX text, for i in will pass one line at a time into the body of the block. Pretty sweet, right? Redirect the output of that whole statement into another text file and you’ll have your list of IPs!

0 Responses to “Resolve 750 Domains in One Line”


  1. No Comments

Leave a Reply