Pages

Blog is moving

My blog is moving to http://victormendonca.com/blog/. If you are looking for a specific or older post you are in the right place Otherwise check out my new page for more up to date content.

Sunday, March 23, 2008

How to get email and sms notifications from your server

Ever wondered if you could make you server send you an email or a sms to your cell phone if it ever went down, or if you logs folder were too big, or any other event that you can think? Well, here's a really simple way of doing so.

In my case, I'll be using two events, one if the server goes down, and another if my logs folder gets too big (I have a very simple Linux box that does not have file rotation).

1- Mayday, server is down

There are two ways we can do this, and it will depend on how often do you need to check if the server is down. If you need it to be done every minute or so, I'd advise using a service instead of crontab. I could not personally say what's the system hog difference, but I'm open for feedbacks. In my case I'll be checking every hour, so I'll use crontab.

Other thing required is a cli email client, and there are many you can use. I choose msmtp, which is extremely easy to configure. Here's what I have set to use my gmail account:

So now that we have means to send the message, let's create the script. Remember that the script will need to be run from another PC and not from the server. A server that is down cannot send emails!!

#!/bin/bash

## pings the server IP. Here I'm using only one ping as some distros ping 4x times (Fedora), and others will ping consecutively by default (Ubuntu)ping -c 1 server

## checks if the ping was successful or not, if not it sends an email and a sms with the last time it tried to pingif [ “$?” != “0” ] ; then echo -e "Subject: Server is down \n\n Victor, \n Server is down. Last time tested was $(date)." | msmtp -v me@adreess.ca 12312345678@cellprovider.comfi

Now we add the script to your crontab and send any error msg to a txt. Make sure that your account has pinging privileges