To just iterate over the list with the command that you used on a single host (slightly modified to also include the hostname itself):
while read h; do
host "$h" | awk '{ print $1, $3 }'
done <linux.hosts >outputfile.txt
This reads from linux.hosts
, applies the host
and awk
commands on each entry in there, and saves the result to outputfile.txt
.
Or, if you will, on one line:
while read h; do host "$h" | awk '{ print $1, $3 }'; done <linux.hosts >outputfile.txt
The following is a much more generic approach that takes hostname aliases and multiple IP addresses into account and produces one line of output for each line of input in the supplied file:
Given a list of hosts in hostnames.txt
, such as
www.uu.se
www.kth.se
www.su.se
Then, given a short awk
script (script.awk
),
/^;/ || NF == 0 { next }
$4 == "CNAME" { cn[$5] = (cn[$5] ? cn[$5] "," $1 : $1) }
$4 == "A" { ip[$1] = (ip[$1] ? ip[$1] "," $5 : $5) }
END {
for (i in ip) {
if (cn[i])
printf("%s (%s) = ", i, cn[i])
else
printf("%s = ", i)
print ip[i]
}
}
The bash
command line
dig +noall +answer -f hostnames.txt | awk -f script.awk
would produce
su.se. (www.su.se.) = 193.11.30.171
www.kth.se. = 130.237.28.40
live.webb.uu.se. (www.uu.se.) = 130.238.7.135,130.238.7.133,130.238.7.134
This takes host name aliases and hosts with multiple IP addresses into account. The host name aliases are the names in parentheses.
The dig
command by itself would produce the output
; <<>> DiG 9.4.2-P2 <<>> www.uu.se +noall +answer
;; global options: printcmd
www.uu.se. 300 IN CNAME live.webb.uu.se.
live.webb.uu.se. 300 IN A 130.238.7.134
live.webb.uu.se. 300 IN A 130.238.7.135
live.webb.uu.se. 300 IN A 130.238.7.133
www.kth.se. 600 IN A 130.237.28.40
www.su.se. 300 IN CNAME su.se.
su.se. 300 IN A 193.11.30.171
and it does to through a batch query (-f
) on the list of hostnames.
This is what the awk
code parses and summarizes.
The awk
script detects the CNAME
entries for host name aliases and saves a comma-separated list of aliases for each real hostname in the cn
array, and does a similar operation to save the IP addresses in the ip
array for each hostname.
The END
block goes through the hostnames in the ip
array and checks to see whether it has any aliases or not. If it has, these are printed in parenthesis. Then the list of IP numbers are added to the end of the line.