Monitor processes in Linux using Perl script

This is another perl script I wrote to monitor critical processes in Linux and report status to log. This script is alot like the earlier script I wrote to check mount points in that it opens a command and write it to a file in order to use regular expressions to check if something is true or not. Also this script can be edited to monitor any number of process and report it any number of ways including syslog, Nagios, or just system mail.

#!/usr/bin/perl -w
#
#name: processMonitor.pl
#written by trizsolo
#usage: ./processMonitor.pl args args args
#you can add as many processes as needed for args
#or use the defaults... syslogd is always checked
#----------------------------
my $user='root';
my $host=`hostname`;
chomp($host);
my $date=`date`;
chomp($date);
my $logfile="$host" . '.log';
our @proc_list=@ARGV;
# Default list of processes
if(@proc_list==0){ # check for arguments
@proc_list=('inetd', 'sendmail', 'chkMounts.pl');
}
push(@proc_list, 'syslogd'); # add syslogd to check

# ---------- open logfile and determine Operating System --------------
open(LOG, ">>$logfile") or die "Can't open $logfile to write: $!";
print LOG "Searching for: @proc_list on $date!\n";
chomp($os=`uname -r`);
print LOG "OS on this server is $os\n";
close(LOG);

# ---------------- call "ps" & analyse output --------------------
foreach my $process (@proc_list) {
$event_count{$process} = 0;
}
open(PS, "/bin/ps auwx |") or die "Can't run ps: __FILE__ $!";
$/="\n"; # record seperator
while(
) {
foreach my $process(@proc_list) {
if($_ =~(m/$process/i)) {
$event_count{$process}++;
}
}
}
close(PS);
open(LOG,">>$logfile") or die "Cannot open $logfile: $!";
# Add line to log to nagios if needed
foreach $process(@proc_list) {
if($event_count{$process} ==0) {
print LOG "Process $process is NOT running!\n";
system("/bin/logger -p warn Process: $process is NOT running!\n")
== 0 or die "Cannot complete cmd: $! : $?";
}else{
print LOG "Process $process occurred $event_count{$process} times!\n";
}
}
close(LOG);
exit 0;
#EOF 

Enjoy and as always if you use my code… please credit triz solo… we likey props!

5 Responses to “Monitor processes in Linux using Perl script”

  1. I think

    $/=”\n”; # record seperator
    while(
    ) {

    should be

    $/=”\n”; # record seperator
    while()
    {

  2. Definitely… I don’t see why I would have done that on purpose.

  3. Bhavesh Says:

    Instead of this

    while(
    ) {


    use


    while() {

    then it will work properly.

  4. I needed to update update the line as

    while()

    To make it work.

    Very useful script, Thanks.

  5. WordPress seems to have removed the important part. But you need to add PS enclosed in pointy brackets between the curly brackets in the while. Hope that make sense.

Leave a Reply