【shell脚本】从命令行输入ip或读取文件ping Ip地址是否通ping.sh

一、只从文件读取

[root@rhel8 shell]# cat ping.sh 
#!/bin/bash

# 判断是否有输入参数
if [ $# -eq 0 ];then

#    basename:只输出路劲的最后一个名称
    echo -e "33[34mUsage: `basename $0` filename.txt33[0m"    
fi

# 判断是否输入的是文件
if [ ! -f $1 ];then
    echo -e "33[33mError file(It's not a file)33[0m"
    exit    
fi

# 从文件读取ip地址
for ip in `cat $1`
do
    ping -c2 $ip >/dev/null 2>&1
    if [ $? -eq 0 ];then
        echo -e "33[33m${ip} is up33[0m"
    else
        echo -e "33[33m${ip} is down33[0m"
    fi
done

二、从命令行或文件读取

[root@rhel8 shell]# cat ping.sh 
#!/bin/bash

IP_REG=([0-9]{1,3}.){3}[0-9]{1,3}
# 判断是否有输入参数
if [ $# -eq 0 ];then

#    basename:只输出路劲的最后一个名称
    echo -e "33[34mUsage: `basename $0` filename.txt|ipaddr33[0m"    
    exit
fi

# 判断是$1是否输入参数,输入的参数是ip地址还是文件
# 判断输入的是IP地址
if [[ $1 =~ $IP_REG ]];then
    ping -c2 -W1 $1 >/dev/null 2>&1
    if [ $? -eq 0 ];then
        echo -e "33[33m$1 is up33[0m"
        else
        echo -e "33[33m$1 is down33[0m"
    fi
elif [ -f $1 ];then
    # 从文件读取ip地址
    for ip in `cat $1`
    do
        ping -c2 $ip >/dev/null 2>&1
        if [ $? -eq 0 ];then
            echo -e "33[33m${ip} is up33[0m"
        else
            echo -e "33[33m${ip} is down33[0m"
        fi
    done
else
    # basename:只输出路径的最后一个名称
    echo -e "33[34mUsage: `basename $0` filename.txt|ipaddr33[0m"
    exit
fi
原文地址:https://www.cnblogs.com/HeiDi-BoKe/p/13176535.html