host unix.stackexchange.com
会为您提供以下结果:
unix.stackexchange.com has address 198.252.206.140
我想在bash脚本中使用此命令,该脚本将读取hostname.txt,其中列出了多个主机名,如下所示:
server1
server2
server3
server4
server5
我希望它能将结果输出到屏幕或其他txt文件。
答案 0 :(得分:1)
以下是执行您要求的简单代码段:
cat hostname.txt | while read line
do
host $line | grep ' address '
done >output.txt
如果您想要所有输出,请移除grep
过滤器,它就在那里,以匹配您在问题中提出的要求。
答案 1 :(得分:0)
这是一个保存为脚本并生成可执行文件的代码片段,它将生成您请求的输出。我通过|
添加了输出管道grep
,以过滤掉host
中可能发生的其他输出。
cat hostname.txt | while read line; do
x="$(host "$line")"
echo "$x" | grep 'address'
done
假设hostname.txt
文件包含:
google.com
yahoo.com
stackoverflow.com
写入的输出将是:
google.com has address 216.58.219.142
google.com has IPv6 address 2607:f8b0:4008:808::200e
yahoo.com has address 98.138.253.109
yahoo.com has address 206.190.36.45
yahoo.com has address 98.139.183.24
stackoverflow.com has address 198.252.206.140
没有管道|
通过grep
输出:
google.com has address 216.58.219.142
google.com has IPv6 address 2607:f8b0:4008:808::200e
google.com mail is handled by 20 alt1.aspmx.l.google.com.
google.com mail is handled by 10 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.
google.com mail is handled by 50 alt4.aspmx.l.google.com.
yahoo.com has address 206.190.36.45
yahoo.com has address 98.139.183.24
yahoo.com has address 98.138.253.109
yahoo.com mail is handled by 1 mta5.am0.yahoodns.net.
yahoo.com mail is handled by 1 mta7.am0.yahoodns.net.
yahoo.com mail is handled by 1 mta6.am0.yahoodns.net.
stackoverflow.com has address 198.252.206.140
stackoverflow.com mail is handled by 10 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 5 alt1.aspmx.l.google.com.
stackoverflow.com mail is handled by 1 aspmx.l.google.com.
stackoverflow.com mail is handled by 5 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 10 aspmx3.googlemail.com.
执行脚本时,您可以通过例如:
重定向输出scriptname > output.txt
您可以将cat hostname.txt
更改为cat $@
,然后使用该脚本,例如:
scriptname hostname.txt
或者:
scriptname hostname.txt > output.txt