对于判断主机是否存活的时候,不能只ping一次就下结论,对于其他业务类似。因此应该增加重试次数。采用三种方式实现。
判断主机存活(1)
#/bin/bash # date: 2022年1月14日21:28:42 # author: ninesun # desc: ping 主机ip超过三次ping不通再失败 while read ip;do ping_count=0 for i in {1..3};do ping -c1 -W1 $ip >& /dev/null if [ $? -eq 0 ];then echo "$ip ping successful!" break #跳出for循环 else echo "$ip is failed! $i" let ping_count++ fi done done <ip.txt
判断主机存活(2)
#!/bin/bash ping_process() { ping -c1 -W1 $ip >& /dev/null if [ $? -eq 0 ];then echo "$ip ping successful!" continue >& /dev/null # 跳过本次循环 fi } while read ip;do ping_process ping_process ping_process echo "$ip ping failed!" done <ip.txt
判断主机存活(3)
#!/bin/bash while read ip;do for i in {1..3};do ping -c1 -W1 $ip >&/dev/null if [ $? -eq 0 ];then echo "$ip ping suucessful" break else echo "$ip ping failed $i" fail_count[i]=$ip fi done if [ ${#fail_count[*]} -eq 3 ];then echo "$ip ping failed!" unset fail_count[*] fi done <ip.txt ~