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
:
root=youremail@gmail.com mailhub=smtp.gmail.com:587 AuthUser=youremail@gmail.com AuthPass=yOuRfUnKyP4ssWorD UseTLS=YES UseSTARTTLS=YES AuthMethod=LOGIN
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" yourothermail@gmail.com
2. The Script
This time we use Bash, because you might not realize that you’re already fluent with Bash.
#!/bin/bash # check and send ip address to email MYIP=`ifconfig eth0 | grep 'inet addr'| awk '{print $2}' | cut -d ':' -f 2`; TIME=`date`; LASTIPFILE='/home/yourUserName/.last_ip_addr'; LASTIP=`cat ${LASTIPFILE}`; if [[ ${MYIP} != ${LASTIP} ]] then echo "New IP = ${MYIP}" echo "sending email.." echo -e "Hello\n\nTimestamp = ${TIME}\nIP = ${MYIP}\n\nBye" | \ /usr/bin/mail -s "[INFO] New IP" yourothermail@gmail.com; echo ${MYIP} > ${LASTIPFILE}; else echo "no IP change!" fi
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/emailipaddr.sh
Sources: