Created
March 6, 2015 11:34
-
-
Save JakeSidSmith/2c31a7258ea600703cec to your computer and use it in GitHub Desktop.
Little python program for logging internet connection
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 urllib2, time, socket | |
from datetime import datetime | |
previous_state = 'Monitoring started' | |
current_state = 'Monitoring started' | |
readable_time = None | |
time_now = None | |
disconnected_time = None | |
def start_monitoring(): | |
global previous_state, current_state, readable_time, time_now, disconnected_time | |
time_now = datetime.now() | |
readable_time = datetime.strftime(time_now, "%Y/%m/%d - %H:%M:%S") | |
file = open('connection-log.txt', 'a') | |
file.write(readable_time + ' - Monitoring started\n') | |
file.close() | |
print(readable_time + ' - ' + current_state) | |
while True: | |
time_now = datetime.now() | |
readable_time = datetime.strftime(time_now, "%Y/%m/%d - %H:%M:%S") | |
current_state = internet_connected() | |
if (current_state != previous_state): | |
file = open('connection-log.txt', 'a') | |
if (current_state == True): | |
if (disconnected_time): | |
disconnected_for = time_now - disconnected_time | |
disconnected_for_string = ('%s' % (disconnected_for)).split('.')[0] | |
print('Disconnected for: ' + disconnected_for_string + '\n') | |
file.write('Disconnected for: ' + disconnected_for_string + '\n') | |
print(readable_time + ' - Connected') | |
file.write(readable_time + ' - Connected\n') | |
file.close() | |
elif(current_state == False): | |
disconnected_time = time_now | |
print(readable_time + ' - Disconnected') | |
file.write(readable_time + ' - Disconnected\n') | |
file.close() | |
else: | |
file.close() | |
previous_state = current_state | |
time.sleep(5) | |
def internet_connected(): | |
global readable_time | |
try: | |
response=urllib2.urlopen('http://google.com/',timeout=1) | |
return True | |
except urllib2.URLError as err: | |
pass | |
return False | |
except socket.timeout as err: | |
pass | |
file = open('connection-log.txt', 'a') | |
print('Connection timed out') | |
file.write('Connection timed out\n') | |
file.close() | |
return False | |
return False | |
start_monitoring() |
Monitor should be an object so that global
values can be stored on this
.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Create
toReadableDateTime
function.