Resolving Domains: File Write Output to txt File
In this article, we will discuss how to resolve domains using a bash script and how to write the output to a text file. The script we will examine changes its directory to the script's location, reads a list of fully qualified domain names (FQDNs) from a file, resolves each FQDN, and writes the resolved IP addresses to another file.
The Bash Script
Here's the bash script that performs the tasks mentioned above:
#!/bin/bash
# Changes script's directory
cd /var/www/html/fqdn || exit
# Input and output files
INPUT\_FILE="fqdnlist.txt"
OUTPUT\_FILE="resolvedfqdnlist.txt"
First, the script sets its working directory to the directory where the script is located. This ensures that the script can find the input and output files relative to its location. Next, it defines the input file (which contains the FQDNs) and the output file (which will contain the resolved IP addresses).
# Read FQDNs from input file
while read -r fqdn
do
# Resolve FQDN
ip\_address=$(getent hosts $fqdn | awk '{ print $1 }' | head -n 1)
# Write IP address to output file
echo $ip\_address >> $OUTPUT\_FILE
done < $INPUT\_FILE
The script then reads each FQDN from the input file, resolves it using the getent command, extracts the resolved IP address, and writes it to the output file. The getent command looks up the FQDN in the system's hosts file (/etc/hosts) and returns the corresponding IP address. The awk command extracts the IP address from the output of getent by printing the first field (the IP address) of the line. The head command takes only the first line of output, because getent returns multiple lines if there are several IP addresses associated with the same FQDN.
Input and Output Files
The input file (fqdnlist.txt) is a simple text file that contains one FQDN per line:
example.com google.com github.com
The output file (resolvedfqdnlist.txt) is another text file that contains one resolved IP address per line:
93.184.216.34 172.217.3.206 140.82.112.4
Summary and References
In this article, we have discussed how to resolve domains using a bash script and how to write the output to a text file. The script uses the getent command to resolve the FQDNs and writes the resolved IP addresses to the output file. We have also covered the input and output files used by the script.