Monday, 6 July 2015

[How To] E-Mail Alerts on a CentOS Server



Required :
- sSMTP (install using yum from epel repo)
- bash script and cron

First :
Enable epel-repo :

Centos 6.x 32 Bit :
#wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
#rpm -ivh epel-release-6-8.noarch.rpm

Centos 6.x 64 Bit :
#wget http://download.fedoraproject.org/pub/epel/6/x86_64/epel-release-6-8.noarch.rpm
#rpm -ivh epel-release-6-8.noarch.rpm

and than install ssmtp
#yum -y update
#yum -y install ssmtp


Change your default Mail Transfer Agent (MTA) to ssmtp
[root@ademahmudf ~]# alternatives --config mta

There are 2 programs which provide 'mta'.

  Selection    Command
-----------------------------------------------
*  1           /usr/sbin/sendmail.postfix
 + 2           /usr/sbin/sendmail.ssmtp

Enter to keep the current selection[+], or type selection number: 2

Next, configure the mail server info to relay outgoing email (i use gmail for example)
#mv /etc/ssmtp/ssmtp.conf /etc/ssmtp/ssmtp.conf.bak
#mv /etc/ssmtp/revaliases /etc/ssmtp/revaliases.bak

#nano /etc/ssmtp/ssmtp.conf
root=postmaster
mailhub=smtp.gmail.com:587
Hostname=example@gmail.com
FromLineOverride=YES
AuthUser=example@gmail.com
AuthPass=email-password
UseSTARTTLS=YES
TLS_CA_File=/etc/pki/tls/certs/ca-bundle.crt

#nano /etc/ssmtp/revaliases
root:example@gmail.com:smtp.gmail.com:587

Next, you can start sending email using your preferred email server using command below
echo "Testing outgoing email from Centos server" | mail -s "Testing" -r sender@gmail.com receiver@gmail.com

And here we go,
Let's create an example script for notification and run with cron

#nano disk_space_notif.sh

#!/bin/bash
CURRENT=$(df / | grep / | awk '{ print $4}' | sed 's/%//g')
THRESHOLD=90

if [ "$CURRENT" -ge "$THRESHOLD" ] ; then
echo "Your partition at server $HOSTNAME is critically low. Used: $CURRENT%" | mail -s "Disk Space Alert" -r sender@gmail.com receiver@gmail.com
fi

make script executable
#chmod +x disk_space_notif.sh

add cronjob for running script
#crontab -e

*  *  *  *  * /path/to/script/disk_space_notif.sh





0 comments:

Post a Comment