Email notification if IP is changed with Python and cron

This Python script retrieves computer’s external IP address (using and emails message with new IP if IP has been changed since last check. BeautifulSoup module is needed, so install it if you have no installed version:

sudo pip install beautifulsoup


#!/usr/bin/env python

from BeautifulSoup import BeautifulSoup
import urllib2
import re
import smtplib
from email.mime.text import MIMEText

logFile = '/var/log/ippywatchdog.log'

request = urllib2.urlopen('')

soup = BeautifulSoup(request)
yandexIpResponse = soup.find('div', {'class': 'b-info__item b-info__item_type_ip'})'[0-9]+.[0-9]+.[0-9]+.[0-9]+', str(yandexIpResponse)).group(0)

prevIp = ip

    with open(logFile,'r') as log:
        prevIp = log.readline()
except IOError:

if (ip != prevIp):
	for recipient in ['<recipient0>', '<recipient1>']:
	    msg = MIMEText('New IP address of Server is ' + ip)
	    msg['Subject'] = 'IP address of Server changed'
	    msg['From'] = '<email>'

	    server = smtplib.SMTP('', 587)
	    server.login(msg['From'], '<email_password>')

	    msg['To'] = recipient
	    server.sendmail(msg['From'], msg['To'], msg.as_string())

with open(logFile, 'w') as log:

Replace <recipient0> and <recipient1> with emails which you want to receive warnings about IP change. You can add more recipients or leave the only one. Replace <email> and <email_password> with real email account and password (you need real account at or similar email provider). SMTP server in the following code is configured for yandex mail.

Now place script to /opt/, make it executable, add to cron.

sudo -s
mv /opt/
chmod +x /opt/
crontab -e

crontab -e will open text editor with cron configuration. Add the following string to execute script every 5 minutes:

*/5 * * * * /opt/