Send Email when IP Address Changes

Posted: 6 Μαρτίου 2018 in linux
Ετικέτες: , , , ,

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”:

sudoapt-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

#!/bin/bash
 
#Script to report public IP address change
#By: Soultidis D. Christos
 

curl ipinfo.io/ip > /home/username/emailscript/erxeteip.txt


oldip=`cat /home/username/emailscript/oldip.txt`
erxeteip=`cat /home/username/emailscript/erxeteip.txt`

if [[ $erxeteip = $oldip ]]
then

    #echo $oldip > /home/username/emailscript/oldip.txt
    echo "Kamia allagi"

else
    echo $erxeteip > /home/username/emailscript/newip.txt
echo $erxeteip > /home/username/emailscript/oldip.txt


    cat /home/username/emailscript/newip.txt | mailx -s "Dynamic Public IP Address" youremail@gmail.com

fi

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

Save this anywhere in your home folder. I personally have my own /home/username/emailscript/

 

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/emailscript/ip.sh >/dev/null 2>&1

ΥΓ. θα πρέπει να δημιουργήσω το oldip.txt

 

Cron daemon is not running. I really screwed up with this some months ago.

Type:

pgrep cron 

If you see no number, then cron is not running. sudo /etc/init.d/cron start can be used to start cron.

EDIT: Rather than invoking init scripts through /etc/init.d, use the service utility, e.g.

sudo service cron start
Advertisements

Τα σχόλια είναι απενεργοποιημένα.