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

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

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

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

# 从文件读取ip地址
for ip in `cat $1`
do
    ping -c2 $ip >/dev/null 2>&1
    if [ $? -eq 0 ];then
        echo -e "\033[33m${ip} is up\033[0m"
    else
        echo -e "\033[33m${ip} is down\033[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 "\033[34mUsage: `basename $0` filename.txt|ipaddr\033[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 "\033[33m$1 is up\033[0m"
        else
        echo -e "\033[33m$1 is down\033[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 "\033[33m${ip} is up\033[0m"
        else
            echo -e "\033[33m${ip} is down\033[0m"
        fi
    done
else
    # basename:只输出路径的最后一个名称
    echo -e "\033[34mUsage: `basename $0` filename.txt|ipaddr\033[0m"
    exit
fi

 

相关文章:

  • 2021-05-28
  • 2021-11-06
  • 2022-12-23
  • 2021-09-18
  • 2022-12-23
  • 2021-11-08
  • 2021-07-19
  • 2022-12-23
猜你喜欢
  • 2021-11-08
  • 2022-01-15
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-02-13
相关资源
相似解决方案