Shell script para monitorear servicios que estan corriendo en Linux con netstat

167

Este shell script monitorea servicios que estan activos en un servidor Linux. 

#!/bin/bash
# Shell script para monitorear servicios que estan corriendo en Linux tales como:
# Dns, Pop3, Imap, web, ssh, mail, mysql, etc.
#
# Si el servicio falla, entonces se envia un email al SysOp
# Last updated: 6/Nov/2009.
# Probe: True
#

#
# Settings
#

ports=”ssh domain http smtp pop3 imap mysql pop3s imaps https”
 
# Nombre de los servicios
service=”SSH DNS HTTP MAIL POP3 IMAP MYSQL POP3S IMAPS HTTPS”
 
#Email del SysOp
ADMINEMAIL=”usuario@midominio.com”
 
NETSTAT=/bin/netstat
MAIL=/usr/bin/mail
LOGGER=/usr/bin/logger
ID=/usr/bin/id
MAIL=/bin/mail
LOGGER=/bin/logger
 
c=1
status=””
sendmail=0
logtosyslog=0
LOG=”/tmp/services.log.$$”
 

log(){
        echo “$@”
        echo “$@” >> $LOG
}
 

die(){
        echo “$@”
        exit 999
}
 

is_root(){
        local id=$($ID -u)
        [ $id -ne 0 ]  && die “You must be root to run $0.”
}

init_script(){
        [ ! -x $MAIL ] && die “$MAIL command not found.”
        [ ! -x $NETSTAT ] && die “$NETSTAT command not found.”
        [ ! -x $LOGGER ] && die “$LOGGER command not found.”
        [ ! -x $ID ] && die “$ID command not found.”
        is_root
        >$LOG
}
 

# Verificamos que todos los servicios esten activos y se envia un email si no estan activos
chk_services(){
        log “————————————————————-“
        log “Running services status @ $(hostname) [ $(date) ]”
        log “————————————————————-“
 
        # Obtenemos los puertos
        RPORTS=$($NETSTAT –tcp –listening –programs | grep -vE ‘^Active|Proto’ | grep ‘LISTEN’ | awk ‘{ print $4}’ | cut -d: -f2 )
 
       
        for t in $ports
        do
                sname=$(echo $service | cut -d’ ‘ -f$c)
                echo -en ” $sname\t\t\t : “
                echo -en ” $sname\t\t\t : ” >> $LOG
                for r in $RPORTS
                do
                        if [ “$r” == “$t” ]
                        then
                                status=”YES”
                                sendmail=1
                                break
                        fi
                done
                echo -n “$status”
                echo “”
                echo -n “$status” >>$LOG
                echo “” >>$LOG
                [ $logtosyslog -eq 1  ] && $LOGGER “$sname service running : $status”
 
              
                c=$( expr $c + 1 )
                status=”NO”
        done
        log “————————————————————-“
        log “This is an automatically generated $(uname) service status notification by $0 script.”
 
        if [ $sendmail -eq 1 ];
        then
                $MAIL -s “Service(s) Down @ $(hostname)” $ADMINEMAIL < $LOG
        fi
}
 
### Programa Principal ###
init_script
chk_services
 
### remove a log file ###
[ -f $LOG ] && /bin/rm -f $LOG