Send Email when IP Address Changes

I have a ubuntu linux box in my office that I occasionally access from home. But unfortunately its IP address is constantly changing due to the dynamic IP allocation policy. Here’s how I set up a “daemon” that will send myself an email upon the change of the machine’s IP address.

1. Setup Gmail and sSMTP

This time we are using sSMTP because it’s easy, and Gmail because it’s free.

I would prefer to create a new Gmail account specific only for this purpose. Use your creativity to create long and obfuscated password, e.g. with mkpasswd -m sha-512 yOuRp4ssW0rD you can get a long string which is should be very nice for password.

Next, install sSMTP and its mail “client”:

sudo apt-get install ssmtp mailutils

Then edit the config file at /etc/ssmtp/ssmtp.conf:

sSMTP is not a daemon, so don’t worry about starting the service or such.

Next, test your setup:

echo "test message" | mail -s "testing ssmtp"

2. The Script

This time we use Bash, because you might not realize that you’re already fluent with Bash.

# check and send ip address to email

MYIP=`ifconfig eth0 | grep 'inet addr'| awk '{print $2}' | cut -d ':' -f 2`;


if [[ ${MYIP} != ${LASTIP} ]]
        echo "New IP = ${MYIP}"
        echo "sending email.."
        echo -e "Hello\n\nTimestamp = ${TIME}\nIP = ${MYIP}\n\nBye" | \
                /usr/bin/mail -s "[INFO] New IP";
        echo ${MYIP} > ${LASTIPFILE};
        echo "no IP change!"

Save this anywhere in your home folder. I personally have my own /home/username/bin/ to keep my small scripts and tools, and I have it in the system path ($PATH).

This script will save your current eth0‘s IP address to the hidden file .last_ip_addr. The next time this script is called, it will check the last IP address, if it’s different then it will notify to the given email address.

3. Cron
To make this run periodically, add the script as a cron job. More detail on cron you can STFG (Search The Fine Google).

crontab -e

Then add this to run the script every 30 minutes

*/30 * * * * /home/username/bin/


Leave a comment

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s

%d bloggers like this: