从文件 ping 多个 IP 地址的 Linux bash 脚本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20629927/
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
Linux bash script that pings multiple IP addresses from a file
提问by Alex
I have a file containing multiple hosts and IPs in the format above:
我有一个包含上述格式的多个主机和 IP 的文件:
alpha, 192.168.1.1
beta, 192.168.1.2
gamma, 192.168.1.3
I am trying to create a script that says something like:
我正在尝试创建一个脚本,内容如下:
"Pinging hostname alpha"
“Ping 主机名 alpha”
ping 192.168.1.1
and jump to the next ip in the list. I don't want the entire script, just some suggestions.
并跳转到列表中的下一个 ip。我不想要整个脚本,只想要一些建议。
Thanks, Alex
谢谢,亚历克斯
采纳答案by Cole Tierney
If you add a comma to the input field separator, it'll help parse the lines:
如果在输入字段分隔符中添加逗号,它将有助于解析行:
IFS=$IFS,
while read name ip; do
echo -n "Pinging hostname $name..."
ping -c2 "$ip" &>/dev/null && echo success || echo fail
done < /tmp/hosts
回答by Charley
I'd read in the lines with read
. You'll probably also want to give ping
an option telling it how many times to ping. The default on most Linux systems for example is to ping forever, which doesn't seem like it would work well in your situation.
我会阅读带有read
. 您可能还想提供ping
一个选项,告诉它要 ping 多少次。例如,大多数 Linux 系统上的默认设置是永远 ping,这在您的情况下似乎不太适用。
回答by Renjith Rajan Pillai
Try this
尝试这个
#!/bin/bash
IPLIST="path_to_the_Ip_list_file"
for ip in $(cat $IPLIST)
do
ping $ip -c 1 -t 1 &> /dev/null
if [ $? -ne 0 ]; then
echo $ip ping faild;
else
echo $ip ping passed;
fi
done
回答by thorbjornwolf
I might be a bit late to the party, but how about fping? Use -f to read from a file (requires sudo), or pipe the file with < (as suggested on the man page). It won't tell you "pinging alpha", but it will quickly tell you whether or not you can get in touch with the hosts.
我参加聚会可能有点晚了,但是fping怎么样?使用 -f 从文件中读取(需要 sudo),或使用 < 管道文件(如手册页中所建议)。它不会告诉您“ping alpha”,但它会很快告诉您是否可以与主机取得联系。
回答by A.D.
You could use AWK:
你可以使用AWK:
$ awk '{print "Pinging hostname "; system("ping -c 3 ") }' ips
Pinging hostname alpha,
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
You can also remove that comma if is it important to you:
如果对您很重要,您也可以删除该逗号:
$ awk '{sub(/,/,"");print "Pinging hostname "; system("ping -c 3 ") }' ips
Pinging hostname alpha
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.