Perl - Processlist watcher samt netstat reader

From Skytech
Jump to navigation Jump to search


Simpelt perl script til overvågning af processer mm

#!/usr/bin/perl
#
# Version:      1.0.0
#

use strict;

## Global wars
my ($iSec, $iMin, $iHour, $iDay) = (localtime(time));

my $iHighLoad = 2.00;
my $sNetstatFile = "/usr/local/sbin/log/netstat.txt-$iDay.$iHour.$iMin";
my $sStatFile = "/usr/local/sbin/log/stat.txt-$iDay.$iHour.$iMin";

####################
my $iLoad = &getLoad();
&checkLoad($iLoad);
####################


sub getLoad() 
{
        my $iLoad = `cat /proc/loadavg | awk '{ print \$1 }'`;
        chomp($iLoad);
        return $iLoad;
}

sub checkLoad()
{
        my $iLoad = shift;

        ## High load - store stuff
        if ($iLoad > $iHighLoad)
        {
                &openFiles();
                &getNetstats($iLoad);
                &getProcCount();
                &getApacheStatus();
                &getTopProcs();
                &closeFiles();
        }
}

sub getNetstats()
{
        my $iLoad = shift;
        my $sNetstat = `netstat -n --numeric-hosts --numeric-ports -p -o`;
        chomp ($sNetstat);
        print statfile "******* NETSTAT ( ".localtime()." ) ******\n";
        print netstat $sNetstat;
        print statfile "*** LOAD currently at ( $iLoad ) ***** \n";

        ## Get mysql count
        my $iMySQLCount = `cat $sNetstatFile | grep ':3306' | wc -l`;
        chomp $iMySQLCount;
        print statfile "MySQLCount::\t$iMySQLCount\n";

        ## Get apache
        my $iApacheCount = `cat $sNetstatFile | grep ':80' | wc -l`;
        chomp $iApacheCount;
        print statfile "ApacheCount::\t$iApacheCount\n";

}

sub getProcCount()
{       
        my $iApacheProcCount = ` ps -ef | grep apache2 | grep -v root | wc -l`;
        chomp $iApacheProcCount;
        print statfile "ApacheProcCount::\t$iApacheProcCount\n";
}

sub getApacheStatus()
{       
        my $sApacheStatus = `apache2ctl status`;
        chomp $sApacheStatus;
        print netstat " ****** ApacheProcCount *****\n";
        print netstat $sApacheStatus;
}

sub getTopProcs()
{       
        my $sTopProcs = `ps -eo user,pcpu,pid,command | sort -r -k2 | head -21`;
        chomp $sTopProcs;
        print netstat "\n\n***** TOP 20 Procs *****\n";
        print netstat $sTopProcs;
}

sub openFiles()
{       
        open (statfile, ">$sStatFile");
        open (netstat, ">$sNetstatFile");
}

sub closeFiles()
{       
        close (netstat);
        close (statfile);
}