几个月前开始着手做cacti相关的一些工作,使用cacti监控一些重要的网络设备以及服务器。cacti是基于snmp协议的,去轮询采集被监控设备的一些信息(流量 服务器资源使用情况等)。但有时会有一些设备因为轮询响应时间长或者没在规定的时间轮询到,而导致误报为snmp down,而实际并非如此。除了在调整cacti本身一些参数设置外,可以使用perl脚本实时监测这些设备的网络连通性
代码如下:#!usr/bin/perl -w
use Net::Ping;
#因为是一直检测所以条件一直为真
while(1){
$result=''; #用来记录测试的结果
#iphost.txt文件保存了需要检测的设备ip,逐行读取设备的ip,调用测试函数进行测试,将返回的结果记录下来
open(F,"iphost.txt");
while ($temp=) {
$result=$result.&ping_test($temp);
}
close(F);
#完成测试,输出测试结果以及完成时间
print $result." ";
print &get_time." test finish"."\n";
#将每次测试结果覆盖写入state.txt文件
open (FP,"+
print FP $result;
close(FP);
sleep(30);
}
#连通性测试函数,使用的是Net::ping模块
sub ping_test{
my($host)=@_;
$count=0;#用来记录ping不通的次数
$pingtool=Net::Ping->new("icmp");
#每个设备的IP测试五次,如果ping不通,$count自增
for($j=0;$j<5;$j++) {
if(!$pingtool->ping($host)){
$count++;
}
}
#根据$count的值判断是否通过连通性测试,1代表通过测试,0代表没通过,5次ping测试都不通视为该设备连通性测试不通过
if($count==5){
$state=0;
}else {
$state=1;
}
$pingtool->close();
return $state; #$state记录测试结果,并将其返回
}
#获取当前时间的函数
sub get_time{
my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime();
my $date = ($mon+1 .'/'. $mday);
my $time = ($hour.":".$min);
return $date." ".$time;
}
要测试的设备ip以及测试结果分别保存在iphost.txt文件以及state.txt文件,这样一来当有新增设备需要监测时,修改iphost.txt文件即可,然后通过php将测试结果显示在web端,并定时刷新,php代码如下
重要网络设备以及服务器连通性测试//读取刚刚测试的结果
$state_file=file("c:/perllesson/state.txt");
foreach($state_file as $value){
$state=$value;
}
//读取被测试的设备ip
$host_file=file_get_contents("c:/perllesson/iphost.txt");
$host=explode("\n",$host_file);
//将结果输出到表格,unreachable将显示为红色
echo "
echo "
被测设备状态";for($i=0;$i
if($state[$i]==1){
echo "
{$host[$i]}reachable";}else{
echo "
{$host[$i]}unreachable";}
}
echo "
" ;?>
其实测试的代码非常简单,这个测试的结果可以和cacti一块去判断设备是否正常运行,大大提高监测的准确性。此外在实际使用过程中,还可以在perl脚本中加入邮件报警以及短信平台的报警。在工作中遇到问题应该积极的去改善思考。