Bash 读取 hostnames.txt 并将其 IP 输出到屏幕或其他 txt 文件的脚本

Bash scripts that reads hostnames.txt and outputs their IPs to screen or another txt file

host unix.stackexchange.com 在命令行,给你以下结果:

unix.stackexchange.com has address 198.252.206.140

我想在 bash 脚本中使用此命令,该脚本将读取 hostname.txt,其中列出了多个主机名,如下所示:

server1
server2
server3
server4
server5

然后我希望它将结果输出到屏幕或另一个 txt 文件。

这是一个简单的代码片段,可以满足您的要求:

cat hostname.txt | while read line
do
    host $line | grep ' address '
done >output.txt

如果您想要 所有 输出,请删除 grep 过滤器,它正好与您在问题中的要求相匹配。

这是一个保存为脚本并可执行的代码片段,将产生您请求的输出。我通过 grep 添加管道 | 输出以过滤掉可能发生的 host 的其他输出。

cat hostname.txt | while read line; do
    x="$(host "$line")"
    echo "$x" | grep 'address'
done

假设 hostname.txt 文件包含:

google.com
yahoo.com
whosebug.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
whosebug.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.
whosebug.com has address 198.252.206.140
whosebug.com mail is handled by 10 aspmx2.googlemail.com.
whosebug.com mail is handled by 5 alt1.aspmx.l.google.com.
whosebug.com mail is handled by 1 aspmx.l.google.com.
whosebug.com mail is handled by 5 alt2.aspmx.l.google.com.
whosebug.com mail is handled by 10 aspmx3.googlemail.com.

执行脚本时,您可以通过以下方式重定向输出:

scriptname > output.txt

您可以将 cat hostname.txt 更改为 cat $@ 以使用脚本,例如:

scriptname hostname.txt

或:

scriptname hostname.txt > output.txt