Skip to content

Instantly share code, notes, and snippets.

@boyd
Created October 22, 2012 03:27
Show Gist options
  • Save boyd/3929478 to your computer and use it in GitHub Desktop.
Save boyd/3929478 to your computer and use it in GitHub Desktop.
Script for monitoring internet
import datetime
import time
import urllib2
def log(s, ts=None):
ts = datetime.datetime.now()
print ts.strftime("%H:%M:%S ") + s
def main():
last_state_change = time.time()
last_state = None
while 1:
start = time.time()
try:
s = urllib2.urlopen("https://www.google.com", timeout=5)
log("up", start)
state = "up"
except urllib2.URLError:
state = "down"
log("error", start)
if last_state != state:
time_since = (start - last_state_change ) / 60
msg = "state changed from {0!s} to {1!s} after {2!s} minutes".format(last_state, state, time_since)
log(msg, start)
last_state = state
last_state_change = start
time.sleep(max(0.001, 15 - (time.time() - start)))
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment