Tuesday 13 November 2018

host command as an alternative to nslookup

The nslookup command is the go to command for performing hostname/IP address lookups. It's a standard command found in Linux, UNIX and Windows distributions alike. While writing scripts we may come across requirements wherein we need the hostname and IP address information to be extracted from the output of the command.

If we use nslookup for this purpose then we would need to employ some interesting awk or grep commands to get the desired result. Given below is an example:

[root@lpic ~]# nslookup google.com
Server:         192.168.178.1
Address:        192.168.178.1#53

Non-authoritative answer:
Name:   google.com
Address: 172.217.24.238

[root@lpic ~]# nslookup google.com | awk '/Address/ && !/#/ {print $2}'
172.217.160.206
[root@lpic ~]#

On the contrary now let's talk about the host command. host is a simple utility for performing DNS lookups. It is normally used to convert names to IP addresses and vice versa. But I found it's output easier to read and extract desired fields from it. Here's an example:

[root@lpic ~]# host google.com
google.com has address 172.217.24.238
google.com has IPv6 address 2404:6800:4002:803::200e
google.com mail is handled by 10 aspmx.l.google.com.
google.com mail is handled by 20 alt1.aspmx.l.google.com.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
google.com mail is handled by 40 alt3.aspmx.l.google.com.
google.com mail is handled by 30 alt2.aspmx.l.google.com.
[root@lpic ~]#
[root@lpic ~]# host google.com | awk '/has address/ {print $4}'
172.217.24.238
[root@lpic ~]#

I hope this quick tip has been helpful for you.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...