bash 脚本从文本文件读取/ping ip 地址列表,然后将结果写入另一个文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19210178/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
bash script to read/ping a list of ip addresses from a text file and then write the results to another file?
提问by user2133606
I have a text file with a lists of IP addresses called address.txt which contains the following
我有一个文本文件,其中包含一个名为 address.txt 的 IP 地址列表,其中包含以下内容
172.26.26.1 wlan01
172.26.27.65 wlan02
172.26.28.180 wlan03
I need to write a bash script that reads the only IP addresses, ping them and output to a another text file to something like this:
我需要编写一个 bash 脚本来读取唯一的 IP 地址,ping 它们并输出到另一个文本文件,如下所示:
172.26.26.1 IS UP
172.26.27.65 IS DOWN
172.26.28.180 IS DOWN
172.26.26.1 已上线
172.26.27.65 已关闭
172.26.28.180 已关闭
I am fairly new to bash scripting so I am not sure where to start with this. Any help would be much appreciated.
我对 bash 脚本很陌生,所以我不确定从哪里开始。任何帮助将非常感激。
回答by janos
In Linux this would work:
在 Linux 中,这会起作用:
awk '{print }' < address.txt | while read ip; do ping -c1 $ip >/dev/null 2>&1 && echo $ip IS UP || echo $ip IS DOWN; done
I don't have a cygwin now to test, but it should work there too.
我现在没有要测试的 cygwin,但它也应该在那里工作。
Explanation:
解释:
- With
awk
we get the first column from the input file and pipe it into a loop - We send a single
ping
to$ip
, and redirect standard output and standard error to/dev/null
so it doesn't pollute our output - If
ping
is successful, the command after&&
is executed:echo $ip IS UP
- If
ping
fails, the command after||
is executed:echo $ip IS DOWN
- 随着
awk
我们从输入文件和管道它的第一列成一个圈 - 我们发送一个
ping
to$ip
,并将标准输出和标准错误重定向到,/dev/null
这样它就不会污染我们的输出 - 如果
ping
成功,则执行之后的命令&&
:echo $ip IS UP
- 如果
ping
失败,则执行 after 命令||
:echo $ip IS DOWN
Somewhat more readable, expanded format, to put in a script:
放在脚本中的更具可读性的扩展格式:
#!/bin/sh
awk '{print }' < address.txt | while read ip; do
if ping -c1 $ip >/dev/null 2>&1; then
echo $ip IS UP
else
echo $ip IS DOWN
fi
done