Disk Usage analyzer mailer for Linux- SMTP

Getting a mail when hard Disk space cross certain percentage. The best way is to have a script that runs under crontab in each hour. So here goes the script I uses. Primary scripts run at cron in it calls second script(python) that send smtp mail. The code as whole is not mine. I got from internet and consolidated it for my need.

Note: In first script the paths “/usr/bin/python  and /home/ubuntu/mail.py” can be updated based on the path of python installation and where the SMTP mailer python script.

First Script

#!/bin/bash
ADMIN=”TO Mail Address”
# set alert-level 90 % standard
ALERT=10
df -H | grep -vE ‘^Filesystem|tmpfs|cdrom’ | awk ‘{ print $5 ” ” $6 }’ | while read output;
do
usep=$(echo $output | awk ‘{ print $1}’ | cut -d’%’ -f1 )
partition=$(echo $output | awk ‘{ print $2 }’ )
if [ $usep -ge $ALERT ]; then
/usr/bin/python /home/ubuntu/mail.py “space low on server $(ifconfig | grep ‘inet addr’ |grep -v 127| awk ‘{print $2}’ | cut -d ‘:’ -f2) at $(date)” “Alert: Free space low, $usep % used on $partition” $ADMIN
fi
done

 

Second Script -python

#!/usr/bin/python
from smtplib import SMTP
import datetime
import sys
smtp = SMTP()
smtp.set_debuglevel(debuglevel)
smtp.connect(‘SMTP IP’, PORT)
from_addr = “Name of Mailer <Mailer@domain.com>”

to = sys.argv[3]
subj = sys.argv[1]
date = datetime.datetime.now().strftime( “%d/%m/%Y %H:%M” )
message_text = sys.argv[2]
msg = “From: %s\nTo: %s\nSubject: %s\nDate: %s\n\n%s” % ( from_addr, to_addr, subj, date, message_text )
smtp.sendmail(from_addr, to_addr, msg)
smtp.quit()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s