【需求描述】
统计10.240.210.171-180/24段的可用IP
【思路方法】
利用ping命令,如果结果返回为真(即[ $? -eq "0" ]),证明该IP对应的主机或终端是存活的,之后将对应IP追加到host_alive_lan.txt文件中,否则则将其追加到host_dead_lan.txt文件中,host_dead_lan.txt文件中的IP即为可用IP,用于分配给新机器。
【code】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
#!/bin/bash
.
/etc/init
.d
/functions
>host_alive_lan.txt
>host_dead_lan.txt
for
n
in
$(
seq
171 180)
do
ip=
"10.240.210.${n}"
#echo ${ip}
ping
-c 1 -w 2 ${ip} &>
/dev/null
if
[ $? -
eq
"0"
];
then
echo
"$ip"
>>host_alive_lan.txt
action
"10.240.210.${n}"
/bin/true
else
echo
"$ip"
>>host_dead_lan.txt
action
"10.240.210.${n}"
/bin/false
fi
done
host_alive_num=$(
wc
-l host_alive_lan.txt|
awk
'{print $1}'
)
host_dead_num=$(
wc
-l host_dead_lan.txt|
awk
'{print $1}'
)
echo
"***************The number of alive host is $host_alive_num***********"
echo
"***************The number of dead host is $host_dead_num************"
/bin/mail
-s
"内网未使用ip列表-`date +'%F %T'`"
-r
"urname@urdomain.com"
user1@urdomain.com user2@urdomain.com < host_dead_lan.txt
|
【运行后效果】
【统计一个B类网段可用IP】
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
#!/bin/bash
.
/etc/init
.d
/functions
>host_alive.txt
>host_dead.txt
for
m
in
$(
seq
10 10 240)
do
for
n
in
$(
seq
3 254)
do
ip=
"10.240.${m}.${n}"
#echo ${ip}
ping
-c 1 -w 2 ${ip} &>
/dev/null
if
[ $? -
eq
"0"
];
then
echo
"$ip"
>>host_alive.txt
action
"$ip"
/bin/true
else
echo
"$ip"
>>host_dead.txt
action
"$ip"
/bin/false
fi
done
done
host_alive_num=$(
wc
-l host_alive.txt|
awk
'{print $1}'
)
host_dead_num=$(
wc
-l host_dead.txt|
awk
'{print $1}'
)
echo
"The number of computer which is on is $host_alive_num"
echo
"The number of computer which is off is $host_dead_num"
/bin/mail
-s
"内网未使用ip列表-`date +'%F %T'`"
-r
"urname@urdomain.com"
user1@urdomain.com user2@urdomain.com < host_dead.txt
|
本文转自 xoyabc 51CTO博客,原文链接:http://blog.51cto.com/xoyabc/1698833,如需转载请自行联系原作者