DNS Query Automation: Using the ‘dig’ Command in Shell Scripts

Shell Scripting @ Freshers.in

The dig command is a powerful tool for querying DNS (Domain Name System) information from the command line. While it’s commonly used interactively, you can also incorporate it into shell scripts to automate DNS-related tasks. In this comprehensive guide, we’ll explore how to use the dig command effectively within shell scripts, providing real-world examples and their respective outputs.

Understanding the ‘dig’ Command

What is the ‘dig’ Command?

The dig command (short for Domain Information Groper) is a versatile DNS query tool available on Unix-like systems. It allows you to query DNS records, retrieve detailed DNS information, and perform various DNS-related tasks.

Basic Usage of ‘dig’

To use the dig command, you typically provide it with the domain name you want to query. Here’s a basic example:

dig example.com

This command will return various DNS-related information for the domain example.com, including its IP address, DNS server, and more.

Using ‘dig’ in Shell Scripts

Incorporating ‘dig’ into Shell Scripts

You can use the dig command within shell scripts by simply calling it within your script’s commands or functions. Let’s explore some common use cases:

Example 1: Querying A and MX Records

#!/bin/bash
domain="example.com"
# Query A record (IPv4 address)
a_record=$(dig +short $domain)
# Query MX records (Mail Exchanger)
mx_records=$(dig +short MX $domain)
echo "A Record for $domain: $a_record"
echo "MX Records for $domain: $mx_records"

Output:

A Record for example.com: 93.184.216.34
MX Records for example.com: 10 mx.example.com.

Example 2: Checking DNS Server Availability

#!/bin/bash
dns_server="8.8.8.8"
# Perform a simple DNS query to check server availability
if dig +short @$dns_server google.com >/dev/null; then
    echo "DNS server $dns_server is reachable."
else
    echo "DNS server $dns_server is not reachable."
fi

Output (if the server is reachable):

DNS server 8.8.8.8 is reachable.

Output (if the server is not reachable):

DNS server 8.8.8.8 is not reachable.

Using the dig command in shell scripts is beneficial for tasks such as:

Automating DNS record lookups and validation.

Monitoring DNS server availability and performance.

Integrating DNS queries into larger automation and scripting workflows.

Author: user