Script batch ping

Batch ping script

If there are many IPs or domain names, we have to determine which ones can be pinged. It is particularly convenient to use automated scripts.

Look at the script first, as shown below:

  • ping_ip.sh
#! /bin/bash
#功能,ping文件ip.lst中的IP,成功的输出到ping_ok.lst文件,失败的输出到ping_fail.lst文件。
echo "" >ping_fail.lst
echo "" >ping_ok.lst
for i in `cat ip.lst` 
do
    ping=`ping -c 1 $i|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`
    if [ $ping -eq 100 ];then
        echo  $i >>ping_fail.lst
    else
        echo $i >>ping_ok.lst
    fi
done 

How to use the script file, put the ip or domain name to be judged in the ip.lst file, the case is as follows:

  • ip.lst
www.baidu.com
180.101.49.12
10.1.1.1

Call the script ping_ip.sh

./ping_ip.sh 

If the script executes the ping command successfully, it returns 0, if it fails, it returns 100. According to the returned result, it will be put in the file ping_ok.lst, and the ping failure will be put in the file ping_fail.lst.

Script content explanation

#! /bin/bash
#功能,ping文件ip.lst中的IP,成功的输出到ping_ok.lst文件,失败的输出到ping_fail.lst文件。
echo "" >ping_fail.lst      #先初始化下两个结果文件,避免多次执行的时候数据混乱问题
echo "" >ping_ok.lst
for i in `cat ip.lst`       #for循环ip.lst 这个文件,这也可以改改,比如 cat iplst |grep -v ^# 将 “#” 开头的行去掉。 
do
    ping=`ping -c 1 $i|grep loss|awk '{print $6}'|awk -F "%" '{print $1}'`   #执行ping命令将ping的 结果放到变量ping中,成功的返回的是0,失败的返回的是100 
    if [ $ping -eq 100 ];then #这个判断就是判断ping是不是等于100,等于就是失败,写入到失败的文件中,否则就是OK,写入OK文件中
        echo  $i >>ping_fail.lst
    else
        echo $i >>ping_ok.lst
    fi
done 

Guess you like

Origin blog.csdn.net/happyjacob/article/details/109063818