列出当前网络上的活动主机

来源:互联网 发布:走进北上广深 知乎 编辑:程序博客网 时间:2024/06/06 02:26

参照《Linux shell 脚本攻略》一书中的例子,写了个检测当前网络上的主机活动状态的脚本,在本机上测试成功,说明如下:


脚本名称:whoisalive.sh
脚本功能:根据输入的 ip 地址,查询当前 IP 地址段内(如 192.168.1.1 ~ 192.168.1.254)的 主机活动状态。
选项说明:
    --all:       列出所有主机的活动状态;
    --alive:    列出所有的活动主机;
    --dead:    列出所有没有在线的主机。
用法说明:
    whoisalive [option] ipaddress
option 为可选选项,不用时,默认为 --all.

一个例子:比如我电脑的当前IP地址为:10.1.1.114,那么在10.1.1.0/24这个网段内,还有那些主机在线呢?我可以以我的IP地址这样查询(推荐使用自己的IP地址)
whoisalive --alive 10.1.1.114
当然,IP地址也可以为 10.1.1.1 ~ 10.1.1.114 内的任何一个,只要合法,用哪个无所谓的。


呵呵,算得上是自己第一个真正意义上的 shell 脚本,记之如下:

#!/bin/bashif [ $# -gt 2 ]then    echo -e "\e[31m ERROR! \e[0m"    echo "Usage: whoisalive [option] ipaddress"    echo option:    echo -e "\t --all:\t\tdisplay all host computer."    echo -e "\t --alive:\tdisplay alive host computer."    echo -e "\t --dead:\tdisplay dead host computer."    echo Note: You can only choose one of the three options, or do not use, and the default value is \"--all\".    echo    echo ipaddress:    echo -e "\t Recommended to use your own ip address. Of course you could use any ip address as you want, but keep in mand, the address is valid."    echo    echo    exit 1fiflag=allwhile truedo    if [ $# -le 0 ]    then        [ "X${ipaddr:-exit}" == "Xexit" ] && exit 0 || break    fi    case $1 in    --all)flag=all;;    --alive)flag=alive;;    --dead)flag=dead;;    -*)echo -e "Error!\nPlease use \"--\" instead of \"-\"";exit 1;;    *)ipaddr=$1;;    esac    shiftdone#echo $flag#echo $ipaddr#echo ${ipaddr%.*}.{1..5}for i in ${ipaddr%.*}.{1..254}do(    ping -c 2 $i &>/dev/null    if [ $? -eq 0 ]    then        [ "X$flag" == "Xall" ] || [ "X$flag" == "Xalive" ] && echo -e "\e[32m $i is alive. \e[0m"    else        [ "X$flag" == "Xall" ] || [ "X$flag" == "Xdead" ] && echo -e "\e[9m $i is down. \e[0m"    fi;)&donewaitexit 0