ping探测在线主机
一.实验要求:
1.对于给定范围的ip地址进行主机在线测试
2.ping测试结果保存在/tmp/ping目录下以时间戳为文件名的文件里,以便后续查看
二.实验过程:
#!/bin/env/ bash
#
#variable declaration
declare -a start_arr
declare -a end_arr
#define function
#IP address initialization
initial_fun(){
read -p "Initial Address:" host_start
read -p "End Address:" host_end
echo -e "Your test segment is : \033[31m${host_start} ~ ${host_end}\033[0m"
}
#Input validation
confirm_fun(){
read -p "Confirm(y);Exit(q);Re-Enter(r): " ack
ack=${ack:="y"}
while [ $ack != "y" -a $ack != "q" -a $ack != "r" ];do
read -p "Confirm(y);Exit(q);Re-Enter(r):" ack
done
}
#IP segmentation
Ip_field(){
local i
for ((i=1;i<=4;i++));do
start_arr[$[i-1]]=`echo $host_start | cut -d. -f $i`
end_arr[$[i-1]]=`echo $host_end | cut -d. -f $i`
done
}
#C class test
Cping_fun(){
local cnet=$1
local i=$2
local j=$3
while [ $i -le $j ];do
if ping -W 1 -c 1 $cnet.$i &> /dev/null;then
echo "$cnet.$i is up." | tee -a /tmp/ping/`date +%F-%H\:%M`.ping
else
echo "$cnet.$i is down."
fi
trap 'exit 1' INT
let i++
done
}
#B class test
Bping_fun(){
local bnet=$1
local i=`echo $2 | cut -d. -f1`
local I=`echo $2 | cut -d. -f2`
local j=`echo $3 | cut -d. -f1`
local J=`echo $3 | cut -d. -f2`
if [ $i -eq $j ];then
Cping_fun $bnet.$i $I $J
else
while [ $i -le $j ];do
Cping_fun $bnet.$i 0 254
let i++
done
fi
}
#main
cat << EOF
Host detetion address vaild range as follows:
B)| 128.0.0.0 ~~ 191.255.255.255
C)| 192.0.0.0 ~~ 223.255.255.255
Please enter your initial address and end address segment detection
such as:192.168.1.1 192.168.1.99
EOF
[ ! -d /tmp/ping ] && mkdir /tmp/ping
initial_fun
confirm_fun
until [ $ack == "y" ];do
if [ $ack == "q" ];then
exit 1
else
initial_fun
confirm_fun
fi
done
[ $ack == "y" ]&& echo "Test is starting..."
Ip_field
if [ ${start_arr[0]} -ge 192 -a ${start_arr[0]} -le 223 ];then
net_addr=${start_arr[0]}.${start_arr[1]}.${start_arr[2]}
flag_start=${start_arr[3]}
flag_end=${end_arr[3]}
Cping_fun $net_addr $flag_start $flag_end
elif [ ${start_arr[0]} -ge 128 -a ${start_arr[0]} -le 191 ];then
net_addr=${start_arr[0]}.${start_arr[1]}
flag_start=${start_arr[2]}.${start_arr[3]}
flag_end=${end_arr[2]}.${end_arr[3]}
Bping_fun $net_addr $flag_start $flag_end
else
echo "Sorry,the detection of such addresses is not supported for the time being."
fi
三.实验总结:递推
四.实验思考:
1.如何进行A类地址测试
2.如何解决超址范围的ip引出的bug
3.能不能给定三个参数,起始ip,结束ip,子网掩码编写个更优的测试脚本