Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python3
- # -*- coding: utf-8 -*-
- import socket, pymysql.cursors, time, sys
- def internet(host="8.8.8.8", port=53, timeout=3):
- try:
- socket.setdefaulttimeout(timeout)
- socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,port))
- return True
- except Exception as ex:
- return False
- def last_record_status(connection):
- with connection.cursor() as cursor:
- sql = "SELECT `status` FROM `record` ORDER BY id DESC"
- cursor.execute(sql)
- result = cursor.fetchone()
- return None if result is None else result['status']
- def get_records(connection):
- with connection.cursor() as cursor:
- sql = "SELECT `*` FROM `record`"
- cursor.execute(sql)
- return cursor
- def write_record(connection, cursor, status):
- sql = "INSERT INTO `record` (`status`) VALUES (%s)"
- cursor.execute(sql, (status))
- connection.commit()
- def get_total_downtime(connection):
- seconds = 0
- cursor = get_records(connection)
- for record in cursor:
- if(record['status'] is 0):
- up = cursor.fetchone()
- seconds += (up['time'] - record['time']).total_seconds()
- return round(seconds / 60);
- def monitor_connection(connection, sleep_time):
- print('Monitoring your connection')
- while True:
- try:
- with connection.cursor() as cursor:
- last_record = last_record_status(connection)
- if not internet():
- if last_record is 1 or last_record is None:
- write_record(connection, cursor, 0)
- else:
- if last_record is 0 or last_record is None:
- write_record(connection, cursor, 1)
- except Exception as ex:
- print(ex)
- time.sleep(sleep_time)
- def args_error():
- print('Please provide an argument\nOptions\n./internet.py monitor\n./internet.py downtime');
- connection = pymysql.connect(host='localhost',
- user='root',
- password='binarystar',
- db='internet',
- charset='utf8mb4',
- cursorclass=pymysql.cursors.DictCursor)
- args = sys.argv;
- if not len(args) > 1:
- args_error()
- elif args[1] == 'monitor':
- monitor_connection(connection, 10)
- elif args[1] == 'downtime':
- print('Remained down for : ' , get_total_downtime(connection) , 'mintues')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement