Linux SysAdmin & DevOps

Perl script - Monitor linux services

If you want to monitor services running on yourlinux machine you have multiple options. But if you don’t want to install any additional software or applications, you can do it with a very simple perl script. (you need MIME::Lite module to be installed though).

In order to install MIME::Lite you have to execute the command bellow using a bash shell:

cpan -i MIME::Lite

Or you can open a perl shell:

perl -MCPAN -e shell

and then issuing:

install MIME::Lite

Create a perl script as follows:

!/usr/bin/env perl

use strict;
use warnings;
use MIME::Lite;
 
#define email address
my $email = '[email protected]';
 
#define services to be monitored
my @services = ('httpd', 'mysql', 'pure-ftpd', 'named', 'lfd', 'exim', 'authdaemond', 'crond', 'spamd', 'upsd', 'snmpd', 'mrtg', 'pptpd', 'vnstatd', 'mrtg', 'monit', 'nagios');
my $host = `/bin/hostname`;
chomp $host;
 
foreach my $service(@services) {
my $status = /bin/ps cax | /bin/grep $service;
if (! $status) {
print "ALERT! $host: $service not running\n";
}
}
 
my $msg = MIME::Lite->new (
Subject => 'Service monitor for $host',
From => 'root@host',
To => $email,
Type => 'text/html',
Data => '',
);
 
$msg->send();

Replace my email with your real email address. Save the scripts as linux-services-monitor.pl, make it executable.

Run the script. If any of your services is not running you will be shown a message on the screen and also an email will be sent to you. The script is really basic and can be highly customized according to your needs.

Have fun!