Thursday, May 27, 2010

MySQL Monitoring Scirpt

#!/usr/bin/perl
use strict;
use warnings;
use POSIX qw(strftime);

#unix command to check the mysql service
my $status = `lsof -i | grep mysql | tr -s ' ' | cut -f 1 -d ' '`;

my $mailprog ='/usr/sbin/sendmail';
my $adminmail = 'user@domain.com';
my $frommail = 'user@domain.com';

my $timestamp = localtime;
my $subject = "WARNING! UNABLE TO CONNECT TO MySQL SERVER AT $timestamp";
my $logfile = 'file';
my $current_time = strftime("%Y-%m-%d %H:%M:%S", localtime());

open (LOGFILE, ">>$logfile");


chomp $status;
if($status eq "mysqld"){
print $status;
print LOGFILE "$current_time, Connection successful\n";
}else{
print "error";
print LOGFILE "$current_time\tConnection failed.";

# code to send the mail
open( MAIL, "|$mailprog -t" );
print MAIL "Subject: WARNING MySQL Server is not responding\n";
print MAIL "From: $frommail\n";
print MAIL "To: $adminmail\n";
print MAIL "Reply-to: $frommail\n\n";
print MAIL "$subject";
print MAIL "\n\n";
close MAIL;
}
close LOGFILE;

No comments: