Bash脚本用于检查主机状态

时间:2016-02-05 20:03:37

标签: bash shell

我有一个文件1.txt,每个ip或主机有一行,即:

yahoo.com
8.8.8.8

我正在尝试编写一个bash脚本,该脚本将解析此文本文件以查看主机是否已启动。我需要它将主机的状态存储在同名文本文件中并无限期地循环该过程。

到目前为止,这是我的进展,不知何故它似乎没有起作用,不知道为什么。

while read ip ; do
        ping -c 1 $ip | grep -E -o '[0-9]+ received' | cut -f1 -d' ' > $ip-status 
$STATUS=$(cat $ip-status)
if [ $STATUS = "1" ]; then
                echo "$ip is UP"
fi
echo "$ip is DOWN!"
done < 1.txt

感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

为什么不采取不同的方法并做这样的事情:

while true; 
do 
    for i in $(cat test); 
    do  
        dig +short +timeout=2 +tries=3 "$i" && 
        echo "$i" is up || 
        echo "$i" is not responding; 
        sleep 2; 
     done; 
done;

以下是测试输出:

$ while true; do for i in $(cat test); do dig +short +timeout=2 "$i" && echo host "$i" is up || echo host "$i" is not responding; sleep 2; done; done
216.58.218.206
host google.com is up
98.138.253.109
98.139.183.24
206.190.36.45
host yahoo.com is up
216.58.218.206
host google.com is up
206.190.36.45
98.138.253.109
98.139.183.24
host yahoo.com is up
216.58.218.206
host google.com is up
98.139.183.24
206.190.36.45
98.138.253.109
host yahoo.com is up

如果您不想要这样的IP,那么您可以将标准输出发送到/ dev / null。

如果您觉得有帮助,请投票。

编辑:

我忘了向您展示我的测试文件:

$ cat test
google.com
yahoo.com
$