Created
November 13, 2015 02:14
-
-
Save yareally/ad36aee3133338ca3410 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding=utf-8 | |
from os import path | |
from time import sleep | |
from urllib.request import urlopen | |
from datetime import datetime | |
from smtplib import SMTP | |
from bs4 import BeautifulSoup | |
DEBUG_TAG = '[{name}]'.format(name=path.basename(__file__)) | |
IP_LOOKUP_URL = 'http://whatismyip.org' | |
def get_external_ip(url: str) -> str: | |
""" | |
:param url: | |
:return: the new ip | |
""" | |
ext_ip = urlopen(url).read() | |
soup = BeautifulSoup(ext_ip, "html.parser") | |
try: | |
return soup.span.string | |
except Exception: | |
log_debug(str(Exception)) | |
def send_email(host='localhost', | |
recipients='[email protected]', | |
sender='[email protected]', | |
msg=''): | |
""" | |
:param host: | |
:param recipients: | |
:param sender: | |
:param msg: | |
""" | |
try: | |
session = SMTP(host) | |
session.sendmail(sender, recipients, msg) | |
log_debug('Sending IP Update email to: {emails}', emails=recipients.split(',')) | |
session.quit() | |
log_debug('Successfully sent!') | |
except Exception: | |
log_debug(str(Exception)) | |
def log_debug(msg: str, **kwargs): | |
""" | |
Logs out what the script is doing in a nice formatted fashion. | |
Use a real logging library to get anymore complex than this. | |
:param msg: the log message as a formatted string | |
:param kwargs: custom data to add to log message | |
:return: | |
""" | |
print('{time}\t{tag}:\t{msg}'.format(tag=DEBUG_TAG, time=datetime.now(), msg=msg.format(**kwargs))) | |
if __name__ == "__main__": | |
before_ip = get_external_ip(IP_LOOKUP_URL) | |
log_debug('Starting up IP Updater') | |
log_debug('Starting IP is: {bip}', bip=before_ip) | |
while True: | |
log_debug('Fetching external IP from: {url}', url=IP_LOOKUP_URL) | |
after_ip = get_external_ip(IP_LOOKUP_URL) | |
if before_ip == after_ip: | |
log_debug('IP is still {ip}. Checking again in an hour...', ip=after_ip) | |
sleep(3600) | |
else: | |
log_debug('IP changed! New IP is: {aip}', aip=after_ip) | |
send_email(msg='Subject: %s\n\n%s' % ("Sir, New IP", "Your new IP is {ip}.".format(ip=after_ip))) | |
sleep(5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment