Skip to content

Instantly share code, notes, and snippets.

@bobbzorzen
Created December 26, 2016 11:51
Show Gist options
  • Save bobbzorzen/305ad996d73938d2a149300f1ff688c2 to your computer and use it in GitHub Desktop.
Save bobbzorzen/305ad996d73938d2a149300f1ff688c2 to your computer and use it in GitHub Desktop.
Small script that tracks network uptime and logs it to file
import time
import datetime
import socket
# import urllib2
def hasInternet(host="8.8.8.8", port=53, timeout=3):
"""
Host: 8.8.8.8 (google-public-dns-a.google.com)
OpenPort: 53/tcp
Service: domain (DNS/TCP)
"""
try:
socket.setdefaulttimeout(timeout)
socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
return True
except Exception as ex:
return False
# def hasInternet2():
# try:
# urllib2.urlopen('http://www.twitch.tv', timeout=1)
# return True
# except urllib2.URLError as err:
# return False
def currentTime() :
return int(round(time.time()))
def getFormatedDateFromInt(timestamp) :
return datetime.datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
def getFormatedDateFromInt2(timestamp) :
hours = int(timestamp / 3600)
timestamp = timestamp % 3600
minutes = int(timestamp / 60)
seconds = timestamp % 60
return str(hours) + ":" + str(minutes) + ":" + str(seconds)
def logToFile(text) :
f = open("networkTimeouts.log", "ab+")
f.write(bytes(text + "\r\n", 'UTF-8'))
timeDeltaStart = 0
print("Starting network logger")
logToFile("Starting network logger")
while True:
if hasInternet() :
if timeDeltaStart != 0 :
#Internet is back
print("Internet returned: ", getFormatedDateFromInt(currentTime()))
logToFile("Internet returned: " + getFormatedDateFromInt(currentTime()))
print("\tTime offline: ", getFormatedDateFromInt2(currentTime() - timeDeltaStart))
logToFile("\tTime offline: " + getFormatedDateFromInt2(currentTime() - timeDeltaStart))
timeDeltaStart = 0
timeDelta = 0
else :
if timeDeltaStart == 0 :
#Lost internet
timeDeltaStart = currentTime()
print("Timeout has started: ", getFormatedDateFromInt(timeDeltaStart))
logToFile("Timeout has started: " + getFormatedDateFromInt(timeDeltaStart))
time.sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment