运维工作中检查主机存活是最为常见的工作,如何快速有效的检查大量主机是否正常就变的非常有必要。因此特写此片博文记录该知识点。

方法1:shell脚本之for循环检查hosts主机存活

[root@saltstack shell]# cat ping_for.sh
#########################################################################
# File Name: ping_for.sh
# Author: mads
# Mail: 1455975151@qq.com
# Created Time: 2016年07月21日 星期四 21时33分03秒
# Description : this is scripts use to
# Version : v1.0
#########################################################################
#!/bin/bash

. /etc/init.d/functions

RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'

array=$(sed '/^#/d' hosts|grep -v "::"|awk '{print $1}')

for host in ${array[@]}
do
        ping $host -c 10 -w 1 -i 0.01 -q >/dev/null 2>&1
        ret=$?
        if [ $ret -eq 0 ];then
                echo "$host is ok"
        else 
                echo "$host is bad"
        fi
done

方法2:shell脚本之while循环检查hosts主机存活

[root@saltstack shell]# cat ping_while.sh
#########################################################################
# File Name: ping_while.sh
# Author: mads
# Mail: 1455975151@qq.com
# Created Time: 2016年07月21日 星期四 21时33分03秒
# Description : this is scripts use to
# Version : v1.0
#########################################################################
#!/bin/bash

. /etc/init.d/functions

RED_COLOR='\E[1;31m'
GREEN_COLOR='\E[1;32m'
YELLOW_COLOR='\E[1;33m'
BLUE_COLOR='\E[1;34m'
RES='\E[0m'

cat hosts| grep -vE "::|#" |while read line
do
        ip=`echo $line|awk '{print $1}'`
        ping -i 0.01 -c 10 -w 1 -q $ip >/dev/null 2>&1
        if [ $? -eq 0 ];then
                echo "$ip is ok"
        else
                echo "$ip is bad"
        fi
done
[root@saltstack shell]# cat hosts
# Do not remove the following line, or various programs
# that require network functionality will fail.
127.0.0.1        master.strong.com master localhost.localdomain localhost
::1        localhost6.localdomain6 localhost6
192.168.80.1      host1.strong.com
192.168.80.2      host2.strong.com
192.168.80.130    host130.strong.com
192.168.80.4      host4.strong.com
192.168.80.5      host5.strong.com
192.168.80.6      host6.strong.com
192.168.80.7      host7.strong.com
192.168.80.8      host8.strong.com
www.baidu.com     www.baidu.com
www.sina.com.cn      www.sina.com.cn
www.2345.com      www.2345.com
方法1和方法2测试文件

相关文章: