Skip to content

Instantly share code, notes, and snippets.

@Mellen
Created July 11, 2020 12:06
Show Gist options
  • Save Mellen/156e9b211fbe72bd4498c65405c0c056 to your computer and use it in GitHub Desktop.
Save Mellen/156e9b211fbe72bd4498c65405c0c056 to your computer and use it in GitHub Desktop.
A script for Sky customers to email out their external IP address when it changes
#! /usr/bin/env python
from urllib.request import urlopen, Request
import urllib
import base64
from bs4 import BeautifulSoup
import os.path
import time
import smtplib
def main():
addr = getIPAddress()
emailIfChanged(addr)
def getIPAddress():
req = Request('http://192.168.0.1/sky_router_status.html')
up_b = base64.b64encode(b'username:password')
up_s = up_b.decode('ascii')
req.add_header('Authorization', 'Basic {up_s}'.format(**{'up_s':up_s}))
try:
resp = urlopen(req).read()
except urllib.error.HTTPError:
# sometimes 401 errors happen on the first attempt
print('401 error, trying again in 10 seconds')
time.sleep(10)
resp = urlopen(req).read()
soup = BeautifulSoup(resp, 'html.parser')
script = soup.find_all('script')[8].contents[0]
lines = script.split('\n')
longvar = lines[12]
parts = longvar.split(' = ')[1].split('_')
return parts[5]
def emailIfChanged(IP):
last_ip = ''
if os.path.isfile('last_ip.txt'):
with open('last_ip.txt', 'r') as ipfile:
last_ip = ipfile.read()
if last_ip == IP:
print('IP not changed ({IP})'.format(**{'IP':IP}))
else:
sendEmail(IP)
with open('last_ip.txt', 'w') as ipfile:
ipfile.write(IP)
def sendEmail(IP):
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
mons = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
recipient = ['my email address']
sender = 'email address I want this to come from'
subject = 'New IP Address at Home'
dt = time.gmtime()
date_str = '{day}, {date:02} {mon} {year} {hour:02}:{minute:02}:{second:02} +0000'.format(**{'day':days[dt.tm_wday], 'date': dt.tm_mday, 'mon': mons[dt.tm_mon-1], 'year':dt.tm_year, 'hour':dt.tm_hour, 'minute':dt.tm_min, 'second':dt.tm_sec})
message = 'From: IPALERT <{sender}>\nTo: My Name <{recipient}>\nSubject: {subject}\nDate: {date}\n\n The IP address has changed to {IP}'.format(**{'sender': sender, 'recipient':recipient[0], 'subject':subject, 'date':date_str, 'IP':IP})
try:
print ('sending email message')
smtp = smtplib.SMTP_SSL('SMTP server address')
smtp.login('username', 'password')
smtp.sendmail(sender, recipient, message)
print('sent message')
except smtplib.SMTPException as ex:
print('failed to send message')
print(ex)
if __name__ == '__main__':
main()
@Mellen
Copy link
Author

Mellen commented Jul 11, 2020

This uses python 3 and requires beautiful soup to be installed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment