As by now you would have known that I have a RaspberryPI connected to my TV running OSMC. I recently had to need to connect to this RPI remotely. So as we all do I punched a hole in my router to the device on the ssh port. I also signed up for DynDNS so I can access the Pi from a URL. But being the tinkerer I am I decided, why not let the Pi tell me it’s public IP address. And just like that a new tinkering project was born! I first created a small php script on my server which returns the IP address of the connecting party, you can check it out here.
php script


Now I had to find a way to get the Pi to connect to this site, collect the returned ip address and check it with some previously stored address for change, and of course email me ONLY when there’s a change. So I created a quick python script to do just that:

import requests
import datetime
import smtplib
from email.mime.text import MIMEText

url = ""
    response = requests.get(url)
    pipaddr = response.text
    f = open('ipadddress','rw+')
    ipaddr = f.readline()
    pipaddr = ''

if(ipaddr <> pipaddr):
    f = open('ipadddress','w')
    print, ipaddr, "=>", response.text
    today =
    to = ''
    gmail_user = ''
    gmail_password = ''
    smtpserver = smtplib.SMTP('', 587)
    smtpserver.login(gmail_user, gmail_password)
    msg = MIMEText(pipaddr)
    msg['Subject'] = 'IP For RPI on %s' % today.strftime('%b %d %Y')
    msg['From'] = gmail_user
    msg['To'] = to
    smtpserver.sendmail(gmail_user, [to] ,msg.as_string())

And this is not all, now this script must be scheduled so it checks the ip then emails me if need be. I did this via good ole cron. There’s a small caveat though with the cron, I had to first change into the directory of the script then run the script or else it would look for the ipaddress file in the current path.

* * * * * cd ~/Scripts/;./ >> log.txt
kimanii Programming, Technology, XBMC

Leave a Reply

Your email address will not be published. Required fields are marked *