使用shell探测活跃的ip
1. 检查ip是否活跃的函数
function is_ip_alive
{
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
[ $? -eq 0 ] && return 0 || return 1
}
2. 一个显示是否活跃的辅助函数
function check_ip_alive
{
if is_ip_alive $1; then
echo "$1 is alive"
else
echo "$1 is not alive"
fi
}
3. 搜索函数
function search_ip_alive
{
local _ip=$1
local _n1=$(echo $_ip | awk -F. '{print $1}')
local _n2=$(echo $_ip | awk -F. '{print $2}')
local _n3=$(echo $_ip | awk -F. '{print $3}')
local _n4=$(echo $_ip | awk -F. '{print $4}')
declare -a _n1_nums=($_n1)
declare -a _n2_nums=($_n2)
declare -a _n3_nums=($_n3)
declare -a _n4_nums=($_n4)
[ $_n1 -eq 256 ] && declare -a _n1_nums=($(seq 0 254))
[ $_n2 -eq 256 ] && declare -a _n2_nums=($(seq 0 254))
[ $_n3 -eq 256 ] && declare -a _n3_nums=($(seq 0 254))
[ $_n4 -eq 256 ] && declare -a _n4_nums=($(seq 0 254))
local _tmp_name=$(mktemp)
for _n1 in ${_n1_nums[@]};do
for _n2 in ${_n2_nums[@]};do
for _n3 in ${_n3_nums[@]};do
for _n4 in ${_n4_nums[@]};do
_ip=$_n1.$_n2.$_n3.$_n4
check_ip_alive $_ip >>${_tmp_name}&
if [ $(jobs |grep check_ip_alive|wc -l) -gt 256 ];then
sleep 1
fi
done
done
done
done
while [ $(jobs |grep check_ip_alive|wc -l) -gt 0 ];do
sleep 1
done
cat ${_tmp_name}|grep "is alive"
rm -f ${_tmp_name}
}
4. 完整的脚本
#! /bin/bash
function is_ip_alive
{
ping -c 3 -i 0.2 -W 3 $1 &> /dev/null
[ $? -eq 0 ] && return 0 || return 1
}
function check_ip_alive
{
if is_ip_alive $1; then
echo "$1 is alive"
else
echo "$1 is not alive"
fi
}
function search_ip_alive
{
local _ip=$1
local _n1=$(echo $_ip | awk -F. '{print $1}')
local _n2=$(echo $_ip | awk -F. '{print $2}')
local _n3=$(echo $_ip | awk -F. '{print $3}')
local _n4=$(echo $_ip | awk -F. '{print $4}')
declare -a _n1_nums=($_n1)
declare -a _n2_nums=($_n2)
declare -a _n3_nums=($_n3)
declare -a _n4_nums=($_n4)
[ $_n1 -eq 256 ] && declare -a _n1_nums=($(seq 0 254))
[ $_n2 -eq 256 ] && declare -a _n2_nums=($(seq 0 254))
[ $_n3 -eq 256 ] && declare -a _n3_nums=($(seq 0 254))
[ $_n4 -eq 256 ] && declare -a _n4_nums=($(seq 0 254))
local _tmp_name=$(mktemp)
for _n1 in ${_n1_nums[@]};do
for _n2 in ${_n2_nums[@]};do
for _n3 in ${_n3_nums[@]};do
for _n4 in ${_n4_nums[@]};do
_ip=$_n1.$_n2.$_n3.$_n4
check_ip_alive $_ip >>${_tmp_name}&
if [ $(jobs |grep check_ip_alive|wc -l) -gt 256 ];then
sleep 1
fi
done
done
done
done
while [ $(jobs |grep check_ip_alive|wc -l) -gt 0 ];do
sleep 1
done
cat ${_tmp_name}|grep "is alive"
rm -f ${_tmp_name}
}
function main
{
search_ip_alive $@
}
main $@
5. 执行效果