Advertisement
Guest User

Untitled

a guest
May 29th, 2017
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. #!/usr/bin/python3
  2. # -*- coding: utf-8 -*-
  3. import socket, pymysql.cursors, time, sys
  4.  
  5.  
  6. def internet(host="8.8.8.8", port=53, timeout=3):
  7. try:
  8. socket.setdefaulttimeout(timeout)
  9. socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host,port))
  10. return True
  11. except Exception as ex:
  12. return False
  13.  
  14. def last_record_status(connection):
  15. with connection.cursor() as cursor:
  16. sql = "SELECT `status` FROM `record` ORDER BY id DESC"
  17. cursor.execute(sql)
  18. result = cursor.fetchone()
  19. return None if result is None else result['status']
  20.  
  21. def get_records(connection):
  22. with connection.cursor() as cursor:
  23. sql = "SELECT `*` FROM `record`"
  24. cursor.execute(sql)
  25. return cursor
  26.  
  27. def write_record(connection, cursor, status):
  28. sql = "INSERT INTO `record` (`status`) VALUES (%s)"
  29. cursor.execute(sql, (status))
  30. connection.commit()
  31.  
  32. def get_total_downtime(connection):
  33. seconds = 0
  34. cursor = get_records(connection)
  35. for record in cursor:
  36. if(record['status'] is 0):
  37. up = cursor.fetchone()
  38. seconds += (up['time'] - record['time']).total_seconds()
  39. return round(seconds / 60);
  40.  
  41. def monitor_connection(connection, sleep_time):
  42. print('Monitoring your connection')
  43. while True:
  44. try:
  45. with connection.cursor() as cursor:
  46. last_record = last_record_status(connection)
  47. if not internet():
  48. if last_record is 1 or last_record is None:
  49. write_record(connection, cursor, 0)
  50. else:
  51. if last_record is 0 or last_record is None:
  52. write_record(connection, cursor, 1)
  53. except Exception as ex:
  54. print(ex)
  55. time.sleep(sleep_time)
  56.  
  57. def args_error():
  58. print('Please provide an argument\nOptions\n./internet.py monitor\n./internet.py downtime');
  59.  
  60. connection = pymysql.connect(host='localhost',
  61. user='root',
  62. password='binarystar',
  63. db='internet',
  64. charset='utf8mb4',
  65. cursorclass=pymysql.cursors.DictCursor)
  66.  
  67. args = sys.argv;
  68. if not len(args) > 1:
  69. args_error()
  70. elif args[1] == 'monitor':
  71. monitor_connection(connection, 10)
  72. elif args[1] == 'downtime':
  73. print('Remained down for : ' , get_total_downtime(connection) , 'mintues')
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement