Skip to content

Instantly share code, notes, and snippets.

@jwmickey
Created January 12, 2015 18:53
Show Gist options
  • Save jwmickey/46c9f847d3b4b0a678bb to your computer and use it in GitHub Desktop.
Save jwmickey/46c9f847d3b4b0a678bb to your computer and use it in GitHub Desktop.
Python script to notify via email when connection resumes
"""
This script determines if your internet connection is up by attempting to open a connection to a specified host.
You can also provide the 'notify' command and an email address to continually monitor for a resumed connection.
I use this specifically to send myself a text in the case where my home connection is out and I went to a coffee
shop, library, etc. in the meantime.
Disclaimer: I'm a python n00b so I'm sure there are better/simpler ways to do this.
License: MIT
"""
import socket
import smtplib
import sys
import urllib2
import string
from time import sleep
REMOTE_IP = '8.8.8.8' # Cannot be hostname, 8.8.8.8 is Google's DNS Server
REMOTE_PORT = 53 # Use 80 if trying a website, 53 is DNS port
GMAIL_USER = 'YOUR_GMAIL_SEND_ADDRESS'
GMAIL_PASS = 'YOUR_GMAIL_SEND_PASSWORD'
RETRY_TIME = 60 # Time between connection attempts (when notification command is sent)
def get_ip():
# lazy way to get ip address. obviously won't work if this service is unreachable
response = urllib2.urlopen("http://api.ipify.org")
return response.read()
def are_we_connected():
try:
s = socket.create_connection((REMOTE_IP, REMOTE_PORT), 2)
s.close()
return True
except:
pass
return False
def notify_when_fixed(email_addr):
while (are_we_connected() != True):
print 'No connection, trying again in %d seconds' % (RETRY_TIME)
sleep(RETRY_TIME)
ip_addr = get_ip()
msg = "Connection is back up! IP address is: %s" % (ip_addr)
print msg
send_notification_email(email_addr, msg)
def send_notification_email(email_addr, message):
body = string.join((
"From: %s" % GMAIL_USER,
"To: %s" % email_addr,
"Subject: Connection Successful",
"",
message
), "\r\n")
try:
s = smtplib.SMTP('smtp.gmail.com', 587)
s.ehlo()
s.starttls()
s.ehlo()
s.login(GMAIL_USER, GMAIL_PASS)
s.sendmail(GMAIL_USER, [email_addr], body)
except Exception,e:
print "ERROR: ",e
finally:
s.quit()
def usage():
print "Usage: "
print " %s - Print True or False if connection is up" % sys.argv[0]
print " %s notify [email] - Try to connect every %d seconds, send email and quit on sucess" % (sys.argv[0], RETRY_TIME)
# MAIN PROGRAM
if (len(sys.argv) == 1):
print are_we_connected()
else:
command = sys.argv[1]
if (command == 'notify'):
if (len(sys.argv) > 2):
notify_when_fixed(sys.argv[2])
else:
print "Error: You must provide the notification email"
elif (command == 'h' or command == 'help'):
usage()
else:
print " - I don't understand that command - \n"
usage()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment