#!/usr/bin/perl
#
# Nagios reporter
# Modified by Felipe Ferreira 04/03/2010
# allows csv of hosts, use html2csv function
#
# Fetches Nagios report from web, processes HTML/CSS and emails to someone
# Written by Rob Moss, 2005-07-26, coding@mossko.com
# Modification: attach .csv results to the email
#
# Version 2.0
#
#use strict;
use Getopt::Long;
use Net::SMTP;
use LWP::UserAgent;
use Date::Manip;
use MIME::Lite;
use HTML::TableExtract;
my $mailhost = 'localhost'; # Fill these in!
my $maildomain = 'localhost'; # Fill these in!
my $mailfrom = 'monitor@localhost'; # Fill these in!
my $mailto = 'monitor@localhost'; # Fill these in!
my $timeout = 30;
my $mailsubject = 'Nagios Report';
my $mailbody = '';
my $logfile ='/usr/local/nagios/var/report.log'; # Where would you like your logfile to live?
my $debug = 1; # Set the debug level to 1 or higher for information
my $type = 'monthly';
my $repdateprev;
my $reporturl;
my $nagssbody;
my $nagsssummary;
my $webuser = 'nagiosadmin'; # Set this to a read-only nagios user (not nagiosadmin!)
my $webpass = 'password'; # Set this to a read-only nagios user (not nagiosadmin!)
my $webbase = 'http://nagios/nagios'; # Set this to the base of Nagios web page
my $webcssembed = 1;
my $rephostgroup = '';
my $reptimeperiod = '';
my $repattach_service = '';
my $repattach_host = '';
my $attachment = '';
my $reporturlink = '';
my $tmpcsvfile = '';
my $tmpcsvfile2 = '';
my $file_conversion = '/usr/lib/nagios/plugins/taula_conversio_ISO8859.txt';
#my $buf = '';
GetOptions (
"debug=s" => \$debug,
"help" => \&help,
"type=s" => \$type,
"email=s" => \$mailto,
"embedcss" => \$webcssembed,
);
if (not defined $type or $type eq "") {
help();
exit;
}
elsif ($type eq "overnight") {
report_overnight();
}
elsif ($type eq "daily") {
report_daily();
}
elsif ($type eq "monthlyservice") {
report_monthly_service();
}
elsif ($type eq "monthlyhost") {
report_monthly_host();
}
else {
die("Unknown report type $type\n");
}
if ($reporturl ne '') {
debug(1,"reporturl: [$reporturl]");
$mailbody = http_request($reporturl);
if ($webcssembed) {
# Stupid hacks for dodgy notes
$nagssbody = http_request("$webbase/stylesheets/summary.css");
$nagsssummary = "\n";
$nagsssummary .= "\n";
$mailbody =~ s@@@;
$mailbody =~ s@@$nagsssummary@;
}
process_hosts_csv();
open(FILE, "> /tmp/nagios-report-htmlout.html") or warn "can't open file /tmp/nagios-report-htmlout.html: $!\n";
print FILE $mailbody;
close FILE;
}
if ($repattach_service)
{
debug(1,"reporturl: [$repattach_service]");
$attachment = http_request($repattach_service);
open(FILE, ">$tmpcsvfile") or warn "can't open file $tmpcsvfile: $!\n";
print FILE $attachment;
close FILE;
process_services_csv();
}
elsif ($repattach_host)
{
$buf = "";
my $csv = '';
#Abri html ao buf
open(IN,"/tmp/nagios-report-htmlout.html");
while() {$buf .=$_}
close(IN);
# pega a tabela como csv e cospe na tela
$csv = &GetHtmlTableAsCsv($buf,0,1);
open(FILECSV, ">$tmpcsvfile") || warn "No puedo abrirel fichero $tmpcsvfile\n";
print FILECSV $csv;
close(FILECSV);
process_hosts_csv();
}
else
{
print "The Report CSV is empty so it will not be processed\n";
};
sendmail();
###############################################################################
sub help {
print <<_END_;
Nagios web->email reporter program.
$0
--help
This screen
--email=
Send to this address instead of the default address
"$mailto"
--type=overnight
Overnight report, from 17h last working day to Today (9am)
--type=daily
Daily report, 08:00-16:00 yestarday (custom)
--type=weekly
Weekly report, last week (custom)
--type=monthly
Monthly report, 1st of prev month at 9am to last day of month, 9am
--embedcss
Downloads the CSS file and embeds it into the main HTML to enable
Lotus Notes to work (yet another reason to hate Notes)
_END_
exit 1;
}
###############################################################################
sub report_monthly_host {
# This should be run on the 1st of every month
$rephostgroup="Liceu_Todos";
$reptimeperiod="24x7";
$repdateprev = DateCalc("yesterday",1);
debug(1,"repdateprev = $repdateprev");
my ($repsday, $repsmonth, $repsyear, $repshour ) = 0;
$repdateprev =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repsday = 01;
$repsmonth = $2;
$repsyear = $1;
$repshour = 0;
my ($repeday, $repemonth, $repeyear, $repehour ) = 0;
my $repdatenow = ParseDate("today");
debug(1,"repdatenow = $repdatenow");
$repdatenow =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repeday = $3;
$repemonth = $2;
$repeyear = $1;
$repehour = 0;
$reporturl = "$webbase/cgi-bin/avail.cgi?show_log_entries=&hostgroup=$rephostgroup&timeperiod=lastmonth&smon=$repsmonth&sday=1&syear=$repsyear" .
"&shour=0&smin=0&ssec=0&emon=$repemonth&eday=$repeday&eyear=$repeyear&ehour=24&emin=0&esec=0&rpttimeperiod=$reptimeperiod&assumeinitialstates=yes&assumestateretention=yes&assumestatesduringnotrunning=yes&includesoftstates=no&initialassumedhoststate=0&initialassumedservicestate=0&backtrack=4";
$tmpcsvfile = "/tmp/nagios-report-host.csv";
$tmpcsvfile2 = "/tmp/nagios-report-host.tmp.csv";
$repattach_host = "GO"; #just so we process as host
$mailsubject = "Disponibilide de servidores - $repsmonth/$repsyear";
}
###############################################################################
sub report_monthly_service {
# This should be run on the 1st of every month
$rephostgroup="Liceu_Todos";
$reptimeperiod="24x7";
$repdateprev = DateCalc("yesterday",1);
debug(1,"repdateprev = $repdateprev");
my ($repsday, $repsmonth, $repsyear, $repshour ) = 0;
$repdateprev =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repsday = 01;
$repsmonth = $2;
$repsyear = $1;
$repshour = 0;
my ($repeday, $repemonth, $repeyear, $repehour ) = 0;
my $repdatenow = ParseDate("today");
debug(1,"repdatenow = $repdatenow");
$repdatenow =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repeday = $3;
$repemonth = $2;
$repeyear = $1;
$repehour = 0;
$reporturl = "$webbase/cgi-bin/avail.cgi?show_log_entries=&hostgroup=Lice_Todos&service=all&timeperiod=lastmonth&smon=$repsmonth&sday=1&syear=$repsyear&shour=0&smin=0&ssec=0&emon=$repemonth&eday=$repeday&eyear=$repeyear&ehour=24&emin=0&esec=0&rpttimeperiod=$reptimeperiod&assumeinitialstates=yes&assumestateretention=yes&assumestatesduringnotrunning=yes&includesoftstates=no&initialassumedhoststate=0&initialassumedservicestate=0&backtrack=4";
$repattach_service = "$webbase/cgi-bin/avail.cgi?show_log_entries=&hostgroup=Lice_Todos&service=all&timeperiod=lastmonth&smon=$repsmonth&sday=1&syear=$repsyear&shour=0&smin=0&ssec=0&emon=$repemonth&eday=$repeday&eyear=$repeyear&ehour=24&emin=0&esec=0&rpttimeperiod=$reptimeperiod&assumeinitialstates=yes&assumestateretention=yes&assumestatesduringnotrunning=yes&includesoftstates=no&initialassumedhoststate=0&initialassumedservicestate=0&backtrack=4&csvoutput=";
$tmpcsvfile = "/tmp/nagios-report-service.csv";
$tmpcsvfile2 = "/tmp/nagios-report-service.tmp.csv";
process_services_csv();
$mailsubject = "Disponibilidad de servicios - $repsmonth/$repsyear";
}
###############################################################################
sub report_weekly {
}
###############################################################################
sub report_daily {
#Report for the day of yestarday, from 8h to 16h
$repdateprev = Date_PrevWorkDay("today",1);
debug(1,"repdateprev = $repdateprev");
#2006072116:48:37
my ($repsday, $repsmonth, $repsyear, $repshour ) = 0;
$repdateprev =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repsday = $3;
$repsmonth = $2;
$repsyear = $1;
$repshour = 8;
my ($repeday, $repemonth, $repeyear, $repehour ) = 0;
# my $repdatenow = ParseDate("today");
# debug(1,"repdatenow = $repdatenow");
# $repdatenow =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repeday = $3;
$repemonth = $2;
$repeyear = $1;
$repehour = 16;
$reporturl = "$webbase/cgi-bin/summary.cgi?report=1&displaytype=3&timeperiod=custom" .
"&smon=$repsmonth&sday=$repsday&syear=$repsyear&shour=$repshour&smin=0&ssec=0" .
"&emon=$repemonth&eday=$repeday&eyear=$repeyear&ehour=$repehour&emin=0&esec=0" .
'&hostgroup=DIBA_Win2k3_Exchange&servicegroup=Criticos&host=all&alerttypes=2&statetypes=2&hoststates=7&servicestates=32&limit=10';
$mailsubject = "SLA Nagios alerts de ayer de las 8h a las 16h";
}
###############################################################################
sub report_overnight {
$repdateprev = Date_PrevWorkDay("today",1);
debug(1,"repdateprev = $repdateprev");
#2006072116:48:37
my ($repsday, $repsmonth, $repsyear, $repshour ) = 0;
$repdateprev =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repsday = $3;
$repsmonth = $2;
$repsyear = $1;
$repshour = 17;
my ($repeday, $repemonth, $repeyear, $repehour ) = 0;
my $repdatenow = ParseDate("today");
debug(1,"repdatenow = $repdatenow");
$repdatenow =~ /(\d\d\d\d)(\d\d)(\d\d)(.*)/;
$repeday = $3;
$repemonth = $2;
$repeyear = $1;
$repehour = 9;
$reporturl = "$webbase/cgi-bin/summary.cgi?report=1&displaytype=1&timeperiod=custom" .
"&smon=$repsmonth&sday=$repsday&syear=$repsyear&shour=$repshour&smin=0&ssec=0" .
"&emon=$repemonth&eday=$repeday&eyear=$repeyear&ehour=$repehour&emin=0&esec=0" .
'&hostgroup=all&servicegroup=all&host=all&alerttypes=3&statetypes=2&hoststates=3&servicestates=56&limit=500';
$mailsubject = "Nagios overnight alerts from $repsday/$repsmonth/$repsyear ${repshour}h to present";
}
###############################################################################
sub http_request {
my $ua;
my $req;
my $res;
my $geturl = shift;
if (not defined $geturl or $geturl eq "") {
warn "No URL defined for http_request\n";
return 0;
}
$ua = LWP::UserAgent->new;
$ua->agent("Nagios Report Generator " . $ua->agent);
$req = HTTP::Request->new(GET => $geturl);
$req->authorization_basic($webuser, $webpass);
$req->header( 'Accept' => 'text/html',
'Content_Base' => $webbase,
);
# send request
$res = $ua->request($req);
# check the outcome
if ($res->is_success) {
debug(1,"Retreived URL successfully");
return $res->decoded_content;
}
else {
print "Error: " . $res->status_line . "\n";
return 0;
}
}
###############################################################################
sub debug {
my ($lvl,$msg) = @_;
if ( defined $debug and $lvl <= $debug ) {
chomp($msg);
print localtime(time) .": $msg\n";
}
return 1;
}
#########################################################
sub GetHtmlTableAsCsv() {
local($bufin,$deep,$count)=@_;
local($buf,$te,$table,@rows,$row);
$te = HTML::TableExtract->new(depth => $deep, count => $count );
$te->parse($bufin);
foreach my $table ($te->tables) {
$buf ="";
my @rows = $te->rows($table);
foreach my $row (@rows) {
$buf .= join(',', @$row). "\n";
}
}
# retorna
return $buf;
}
######################################################
sub sendmail {
my $mime_type ='multipart/mixed';
# Create the initial test of the message
my $mime_msg = MIME::Lite->new(
From => $mailfrom,
To => $mailto,
Subject => $mailsubject,
Type => $mime_type,
)or die "Error creating MIME Body $!\n";
if ($tmpcsvfile) {
my $filename = $tmpcsvfile;
}
# $mime_msg->attach(
# Type =>'text/html',
# Data => $mailbody,
# );
# Attach the file
if ($tmpcsvfile) {
my $filename = $tmpcsvfile;
$mime_msg->attach(
Type => 'text/plain',
Path => $filename,
Filename => "InformesNagios.csv",
Disposition => 'attachment'
)or die "Error attaching file: $!\n";
}
my $message_body = $mime_msg->as_string();
my $smtp = Net::SMTP->new(
$mailhost,
Hello => $maildomain,
Timeout => $timeout,
Debug => $debug,
);
$smtp->mail($mailfrom);
$smtp->to($mailto);
$smtp->data();
$smtp->datasend("To: $mailto\n");
$smtp->datasend("From: $mailfrom\n");
$smtp->datasend("Subject: $mailsubject\n");
$smtp->datasend("$message_body\n");
$smtp->dataend();
$smtp->quit;
}
sub process_services_csv()
{
open(FILE2, ">$tmpcsvfile2") or warn "can't open file $tmpcsvfile: $!\n";
open(FILE, "$tmpcsvfile") or warn "can't open file $tmpcsvfile: $!\n";
#$linia = ;
print FILE2 "Servidor; Servei; Estat OK; Estat WARN; Estat KO; Estat desconegut; Temps sense mostres\n";
while ($linia = ){
@line = split(",",$linia);
if ($line[0] =~ s/Liceu_//) {
$line[1]=~ s/\"//g;
$line[1]=~ s/ //g;
$line[0]=~ s/\"//g;
if (!($line[1] =~ /ping/)) {
$line[10]=~ s/\./,/;
$line[19]=~ s/\./,/;
$line[37]=~ s/\./,/;
$line[28]=~ s/\./,/;
$line[43]=~ s/\./,/;
open(FILE3, "$file_conversion") or warn "can't open file $tmpcsvfile: $!\n";
while ($literals = ){
chop($literals);
($server,$literal_ini,$literal_fin) = split(",", $literals);
if ( "$line[0]" =~ /$server/) {
if ( "$line[1]" eq "$literal_ini") {
$line[1]=$literal_fin;
break;
}
}
}
close FILE3;
print FILE2 "$line[0]; $line[1]; $line[10]; $line[19]; $line[37]; $line[28]; $line[43]";
}
}
}
close FILE;
close FILE2;
`/bin/mv $tmpcsvfile2 $tmpcsvfile`;
}
sub process_hosts_csv()
{
open(FILE2, ">$tmpcsvfile2") or warn "can't open file $tmpcsvfile: $!\n";
open(FILE, "$tmpcsvfile") or warn "can't open file $tmpcsvfile: $!\n";
$linia = ;
print FILE2 "Servidor, Temps OK, Temps KO, Temps inaccessible, Temps sense mostres\n";
while ($linia = ){
($host,$timeup, $timedown,$timeunr,$timeund) = split(",",$linia);
($resto, $tmp)=split('\(', $timeup);
($timeup, $resto)=split('\)', $tmp);
($resto, $tmp)=split('\(', $timedown);
($timedown, $resto)=split('\)', $tmp);
($resto, $tmp)=split('\(', $timeunr);
($timeunr, $resto)=split('\)', $tmp);
$host =~ s/Liceu_//;
$host =~ s/Average/Mitjana/;
$timeup =~ s/\./,/;
$timedown =~ s/\./,/;
$timeunr =~ s/\./,/;
$timeund =~ s/\./,/;
print FILE2 "$host; $timeup; $timedown; $timeunr; $timeund";
}
close FILE;
close FILE2;
`/bin/mv $tmpcsvfile2 $tmpcsvfile`;
}