我正在尝试反向查找主机名列表以找到它们的 IP 并写入文件。我指的是这教程并对其进行扩展以使用主机名列表。我是 Bash 脚本新手,这是我想出的内容,但没有按预期打印,
for name in hostA.com hostB.com hostC.com;
do
host $name | grep "has address" | sed 's/.*has address //' |
awk '{print "allow\t\t" $1 ";" }' > ./allowedip.inc
done
答案1
使用dig
:
for host in hostA.com hostB.com hostC.com
do
# get ips to host using dig
ips=($(dig "$host" a +short | grep '^[.0-9]*$'))
for ip in "${ips[@]}";
do
printf 'allow\t\t%s\n' "$ip"
done
done > allowedip.inc
输出:
$ cat allowedip.inc
allow 64.22.213.2
allow 67.225.218.50
allow 66.45.246.141
循环遍历一个文件,每行一个主机:
while IFS= read -r host;
do
# get ips to host using dig
ips=($(dig "$host" a +short | grep '^[.0-9]*$'))
for ip in "${ips[@]}";
do
printf 'allow\t\t%s\n' "$ip"
done
done < many_hosts_file > allowedip.inc
答案2
grep 的示例:
$ host google.com|grep -oP "has address \K.*"
216.58.214.238