Created
October 22, 2012 03:27
-
-
Save boyd/3929478 to your computer and use it in GitHub Desktop.
Script for monitoring internet
This file contains 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
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