Shell脚本实现 ping功能

Shell 脚本实现 ip ping 功能

具体代码:

#!/bin/bash
# =========================================================
# pingIP_proc.sh
# test the ping in autoMode
# variable in {3}:
#   0 - The 1st - 3st field of ip_addr: such as 172.16.16
#   1 - The last field of Start_IP
#   2 - The last field of End_IP
# =========================================================

RED_COLOR='\E[1;31m'    #红
GREEN_COLOR='\E[1;32m'  #绿
YELOW_COLOR='\E[1;33m'  #黄
BLUE_COLOR='\E[1;34m'   #蓝
PINK='\E[1;35m'         #粉红
RES='\E[0m'

function echo_color(){
    colorType=$1
    echoContext=$2

    if [ $colorType -eq  0  ];then
        echo -e  "${GREEN_COLOR}$echoContext ${RES}"
    elif [ $colorType -eq  1  ];then
        echo -e  "${RED_COLOR}$echoContext ${RES}"
    elif [ $colorType -eq  2  ];then
        echo $echoContext
    elif [ $colorType -eq  3  ];then
        echo -e  "${BLUE_COLOR}$echoContext ${RES}"
    else
        echo -e  "${YELOW_COLOR}$echoContext ${RES}"
    fi
}

ping_Ok_cnt=0
pingOKIP[0]='172.16.16.0'

function pingProc(){
    for ((i=${1};i<=${2};i++)) 
    do
    timeStart=$(date "+ %H:%M:%S")
    ip_dst=${ip_first_three_field}.${i}
    echo_color 3 "ping ${ip_dst} start on ${timeStart}"
    ping=`ping -c 1 $ip_dst|grep loss`
    pingRslt=`ping -c 1 $ip_dst|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`
    if [ $pingRslt -eq 100  ];then
        echo_color 1 "ping ${ip_dst} fail"
    else
        echo_color 0 "ping ${ip_dst} OK"
        pingOKIP[ping_Ok_cnt]=${ip_dst}
        ping_Ok_cnt=`expr $ping_Ok_cnt + 1`
    fi
    #echo ping $ip_dst end
    done
}


# 1. check the input variable
if [ $# -eq 3 ];then
    ip_first_three_field=$1;
    ip_start=$2;
    ip_end=$3;
else
    echo "==========================================="
    echo_color 4 "There is not enough input var ...... $#" 
    echo_color 4 "There need 3 input var ....."
    echo "  0 - IP field of 1 -3: such as: 172.16.16"
    echo "  1 - The last field of Start_IP"
    echo "  2 - The last field of End_IP "
    echo "==========================================="
    exit 
fi

# 2. Call the ping function
timeStart_init=$(date "+%Y-%m-%d %H:%M:%S")
echo $timeStart_init
pingProc $ip_start $ip_end

timeEnd=$(date "+%Y-%m-%d %H:%M:%S")
echo Start: $timeStart_init  End: $timeEnd

# 3. output the ping result
echo_color 4 "ping OK Cnt: [${ping_Ok_cnt}], the IP list:"
ping_OK_num=`expr $ping_Ok_cnt - 1`
for i in $(seq 0 $ping_OK_num)
do
echo "  $i: [ ${pingOKIP[$i] }]"
done

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值