Skip to content

Instantly share code, notes, and snippets.

@trashvin
Forked from waleedahmad/downtime.py
Created May 30, 2019 09:47
Show Gist options
  • Save trashvin/a1d17668fea8e481f0c9c2425a4e1257 to your computer and use it in GitHub Desktop.
Save trashvin/a1d17668fea8e481f0c9c2425a4e1257 to your computer and use it in GitHub Desktop.

Revisions

  1. @waleedahmad waleedahmad revised this gist Sep 1, 2017. 1 changed file with 19 additions and 7 deletions.
    26 changes: 19 additions & 7 deletions downtime.py
    Original file line number Diff line number Diff line change
    @@ -8,6 +8,7 @@
    import socket
    import datetime


    def internet(host="8.8.8.8", port=53, timeout=3):
    """ Generates a new request"""
    try:
    @@ -17,31 +18,37 @@ def internet(host="8.8.8.8", port=53, timeout=3):
    except Exception as ex:
    return False


    def current_timestamp():
    """ Get Current timestamp string """
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")


    def str_to_date(timestamp):
    """ Convert timestamp string to date object """
    return datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")


    def secs_to_HMS(secs):
    """ Convert seconds to second and minuntes
    """ Convert seconds to second and minutes
    Format : HH:MM:SS
    """
    return str(datetime.timedelta(seconds=secs));


    def record_file_exist():
    """ Check if records file exist """
    return os.path.isfile('data.csv')


    def create_record_file():
    """ Create a new record file """
    with open('data.csv', 'a') as csvfile:
    columns = ['timestamp', 'status']
    writer = csv.DictWriter(csvfile, fieldnames=columns)
    writer.writeheader()


    def last_record_status():
    """ Get last record """
    result = None
    @@ -51,12 +58,14 @@ def last_record_status():
    result = row
    return None if result is None else result['status']


    def write_record(status):
    """ Create a new record """
    with open('data.csv', 'a') as csvfile:
    columns = ['timestamp', 'status']
    writer = csv.DictWriter(csvfile, fieldnames=columns)
    writer.writerow({'timestamp' : str(current_timestamp()) , 'status' : status})
    writer.writerow({'timestamp': str(current_timestamp()), 'status': status})


    def get_total_downtime():
    """ Calculate downtime """
    @@ -67,18 +76,19 @@ def get_total_downtime():
    reader = csv.DictReader(csvfile)
    for record in reader:
    try:
    if (record['status'] is '0'):
    if record['status'] is '0':
    print('Went Down at : ', record['timestamp'])
    down = str_to_date(record['timestamp'])
    next_record = next(reader)
    up = str_to_date(next_record['timestamp'])
    seconds += (up - down).total_seconds()
    print('Went up at : ' , next_record['timestamp'])
    print('Went up at : ', next_record['timestamp'])
    except Exception as ex:
    print('\nCurrent Status : Still Down')
    seconds += (str_to_date(current_timestamp()) - down).total_seconds()
    return secs_to_HMS(seconds);


    def monitor_connection(sleep_time):
    """ Start monitoring """
    print('Monitoring your connection')
    @@ -94,15 +104,17 @@ def monitor_connection(sleep_time):
    write_record(1)
    time.sleep(sleep_time)


    def args_error():
    print('Please provide an argument\nOptions\n./internet.py monitor\n./internet.py downtime');
    print('Please provide an argument\nOptions\n./internet.py monitor\n./internet.py downtime')


    args = sys.argv;
    args = sys.argv
    if not len(args) > 1:
    args_error()
    elif args[1] == 'monitor':
    if not record_file_exist():
    create_record_file()
    monitor_connection(1)
    elif args[1] == 'downtime':
    print('\nRemained down for : ', get_total_downtime(), ' HH:MM:SS ' )
    print('\nRemained down for : ', get_total_downtime(), ' HH:MM:SS ')
  2. @waleedahmad waleedahmad revised this gist May 31, 2017. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion downtime.py
    Original file line number Diff line number Diff line change
    @@ -105,4 +105,4 @@ def args_error():
    create_record_file()
    monitor_connection(1)
    elif args[1] == 'downtime':
    print('\nRemained down for : ', get_total_downtime(), ' MM:SS ' )
    print('\nRemained down for : ', get_total_downtime(), ' HH:MM:SS ' )
  3. @waleedahmad waleedahmad revised this gist May 31, 2017. 1 changed file with 2 additions and 5 deletions.
    7 changes: 2 additions & 5 deletions downtime.py
    Original file line number Diff line number Diff line change
    @@ -27,12 +27,9 @@ def str_to_date(timestamp):

    def secs_to_HMS(secs):
    """ Convert seconds to second and minuntes
    Format : MM:SS
    Format : HH:MM:SS
    """
    if secs < 3600:
    return datetime.datetime.fromtimestamp(secs).strftime('%M:%S')
    else:
    return datetime.datetime.fromtimestamp(secs).strftime('%H:%M:%S')
    return str(datetime.timedelta(seconds=secs));

    def record_file_exist():
    """ Check if records file exist """
  4. @waleedahmad waleedahmad created this gist May 31, 2017.
    111 changes: 111 additions & 0 deletions downtime.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,111 @@
    #!/usr/bin/python3
    # -*- coding: utf-8 -*-

    import os
    import csv
    import sys
    import time
    import socket
    import datetime

    def internet(host="8.8.8.8", port=53, timeout=3):
    """ Generates a new request"""
    try:
    socket.setdefaulttimeout(timeout)
    socket.socket(socket.AF_INET, socket.SOCK_STREAM).connect((host, port))
    return True
    except Exception as ex:
    return False

    def current_timestamp():
    """ Get Current timestamp string """
    return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    def str_to_date(timestamp):
    """ Convert timestamp string to date object """
    return datetime.datetime.strptime(timestamp, "%Y-%m-%d %H:%M:%S")

    def secs_to_HMS(secs):
    """ Convert seconds to second and minuntes
    Format : MM:SS
    """
    if secs < 3600:
    return datetime.datetime.fromtimestamp(secs).strftime('%M:%S')
    else:
    return datetime.datetime.fromtimestamp(secs).strftime('%H:%M:%S')

    def record_file_exist():
    """ Check if records file exist """
    return os.path.isfile('data.csv')

    def create_record_file():
    """ Create a new record file """
    with open('data.csv', 'a') as csvfile:
    columns = ['timestamp', 'status']
    writer = csv.DictWriter(csvfile, fieldnames=columns)
    writer.writeheader()

    def last_record_status():
    """ Get last record """
    result = None
    with open('data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
    result = row
    return None if result is None else result['status']

    def write_record(status):
    """ Create a new record """
    with open('data.csv', 'a') as csvfile:
    columns = ['timestamp', 'status']
    writer = csv.DictWriter(csvfile, fieldnames=columns)
    writer.writerow({'timestamp' : str(current_timestamp()) , 'status' : status})

    def get_total_downtime():
    """ Calculate downtime """
    seconds = 0
    down = None
    up = None
    with open('data.csv', 'r') as csvfile:
    reader = csv.DictReader(csvfile)
    for record in reader:
    try:
    if (record['status'] is '0'):
    print('Went Down at : ', record['timestamp'])
    down = str_to_date(record['timestamp'])
    next_record = next(reader)
    up = str_to_date(next_record['timestamp'])
    seconds += (up - down).total_seconds()
    print('Went up at : ' , next_record['timestamp'])
    except Exception as ex:
    print('\nCurrent Status : Still Down')
    seconds += (str_to_date(current_timestamp()) - down).total_seconds()
    return secs_to_HMS(seconds);

    def monitor_connection(sleep_time):
    """ Start monitoring """
    print('Monitoring your connection')
    while True:
    last_record = last_record_status()
    if not internet():
    if last_record is '1' or last_record is None:
    print('Internet went down')
    write_record(0)
    else:
    if last_record is '0' or last_record is None:
    print('Internet is up')
    write_record(1)
    time.sleep(sleep_time)

    def args_error():
    print('Please provide an argument\nOptions\n./internet.py monitor\n./internet.py downtime');

    args = sys.argv;
    if not len(args) > 1:
    args_error()
    elif args[1] == 'monitor':
    if not record_file_exist():
    create_record_file()
    monitor_connection(1)
    elif args[1] == 'downtime':
    print('\nRemained down for : ', get_total_downtime(), ' MM:SS ' )