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.
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:
#!/usr/bin/python import requests import datetime import smtplib from email.mime.text import MIMEText url = "http://220.127.116.11/~meineoas/kimanii/youripaddress" try: response = requests.get(url) pipaddr = response.text f = open('ipadddress','rw+') ipaddr = f.readline() f.close() except: pipaddr = '' if(ipaddr <> pipaddr): f = open('ipadddress','w') f.write(pipaddr) print datetime.datetime.now(), ipaddr, "=>", response.text today = datetime.date.today() f.close() to = 'email@example.com' gmail_user = 'firstname.lastname@example.org' gmail_password = '
' smtpserver = smtplib.SMTP('smtp.gmail.com', 587) smtpserver.ehlo() smtpserver.starttls() smtpserver.ehlo 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()) smtpserver.quit()
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/;./getipaddress.py >> log.txt