sh 按子网Ping IP并显示简单的up / down状态
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sh 按子网Ping IP并显示简单的up / down状态相关的知识,希望对你有一定的参考价值。
#!/bin/bash
# [user@server ~]$ sping.sh 70.120.121.0/29
# 70.120.121.1 down
# 70.120.121.2 up
# 70.120.121.3 up
# 70.120.121.4 up
# 70.120.121.5 up
# 70.120.121.6 up
# configuration variables
# absolute path to directory containing sping.sh, without trailing /
DIR="/usr/local/bin"
# maximum number of concurrent pings
MAX_WORKERS=50
# support programs
declare -A hosts
hosts[30]=1
hosts[29]=5
hosts[28]=13
hosts[27]=29
hosts[26]=61
hosts[25]=125
hosts[24]=253
hosts[23]=509
hosts[22]=1021
hosts[21]=2045
hosts[20]=4093
hosts[19]=8189
hosts[18]=16381
hosts[17]=32765
hosts[16]=65533
hosts[15]=131069
hosts[14]=262141
hosts[13]=524285
hosts[12]=1048573
hosts[11]=2097149
hosts[10]=4194301
hosts[9]=8388605
hosts[8]=16777213
function show_help()
{
echo "usage: sping.sh 192.168.0.0/24"
}
function ip2int()
{
int=0
for octet in ${1//./ }
do
int=$((256*$int+$octet))
done
echo $int
}
function int2ip()
{
echo "$(($1 / 16777216)).$(($(($1 % 16777216)) / 65536)).$(($(($1 % 65536)) / 256)).$(($1 % 256))"
}
function ping_host()
{
ping -c3 -i.2 -W1 -q "$1" 2> /dev/null | grep rtt &> /dev/null
if [ $? -eq 0 ]
then
echo "$1 up"
else
echo "$1 down"
fi
}
function build_list()
{
list=""
start=$(($(ip2int $1)+1))
stop=$(($start+${hosts[$2]}))
for ip in $(seq "$start" "$stop")
do
list+="$(int2ip $ip)\n"
done
echo "$list"
}
# main program
if [ "$1" = "worker" ]
then
result=$(ping_host $2)
echo "$result"
else
IFS='/'
read -a INPUT <<< "$1"
unset IFS
if [ "${#INPUT[@]}" -ne 2 ]
then
show_help
exit 1
elif [ "${INPUT[1]}" = "-h" -o "${INPUT[1]}" = "--help" ]
then
show_help
exit 0
elif [ "${INPUT[1]}" -lt 8 -o "${INPUT[1]}" -gt 30 ]
then
echo "invalid subnet mask"
exit 1
fi
list=$(build_list ${INPUT[0]} ${INPUT[1]})
echo -e "$list" | xargs -n 1 -I ^ -P "$MAX_WORKERS" $DIR/sping.sh worker ^ | sort -t . -k 3,3n -k 4,4n
fi
以上是关于sh 按子网Ping IP并显示简单的up / down状态的主要内容,如果未能解决你的问题,请参考以下文章
linux 怎样设置外网ip、网关、掩码
配置多路由的静态路由
vagrant up 运行时 Ping IP 地址超时
读取带有网络和子网掩码的 csv 并写入带有 ping 结果的文件
ubuntu双网卡双IP.不同网关.不同子网.如何同时ping通两块网卡
如何 ping 和导出跨子网设置的 ip 范围的结果