码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2020-06-22 15:26:20      阅读:171      评论:0      收藏:0      [点我收藏+]

标签:ase   名称   命令行   nbsp   name   rhel   判断   参数   div   

 

一、只从文件读取

[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

 

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

标签:ase   名称   命令行   nbsp   name   rhel   判断   参数   div   

原文地址:https://www.cnblogs.com/HeiDi-BoKe/p/13176535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!