Open In App

Python Script to Monitor Network Connection and saving into Log File

Last Updated : 23 Feb, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to see how to monitor the network connection and save the log file in Python. 

The basic ideology of this script is to give real-time information about if the system the script is being run on is connected to an internet connection or not, and save that information into a log file simultaneously, keeping records of when the system was connected to the internet when it was disconnected and the time duration it was disconnected for.

This script is made using the socket library in Python, which in this program is used to send or receive packets on a network.

Log file:

Starting simply by creating a log file in the current working directory to store the internet connectivity status.

Python




FILE = os.path.join(os.getcwd(), "networkinfo.log")


ping():

Using this function the script will try connecting to the defined server, to check if the system has a live internet connection. This task will be done using exception handling in python (try, except, else). 

  1. The system will try pinging a specific server(PORT at an IP)
  2. If the machine fails to connect, EXCEPT statement will be executed
  3. Else the connection will be closed after the system is successfully connected to the server

 Code:

Python




def ping():
   
    # to ping a particular PORT at an IP
    # if the machine won't receive any packets from
    # the server for more than 3 seconds
    # i.e no connection is
    # made(machine doesn't have a live internet connection)
    # <except> part will be executed
    try:
        socket.setdefaulttimeout(3)
 
        # AF_INET: address family (IPv4)
        # SOCK_STREAM: type for TCP (PORT)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
         
        host = "8.8.8.8"
        port = 53
 
        server_address = (host, port)
         
        # send connection request to the defined server
        s.connect(server_address)
 
    except OSError as error:
       
        # function returning false after
        # data interruption(no connection)
        return False
    else:
       
        # the connection is closed after
        # machine being connected
        s.close()
        return True


Functions Used in above program

  • socket.setdefaulttimeout() : It is an inbuilt socket library function in python. by setting default timeout as 3 seconds, we specify if we do not get any response from the server for more than 3 seconds, the connection is not made.
  • socket.socket(socket.AF_INET, socket.SOCK_STREAM): socket.socket() is used to define parameters to connect two nodes in a network, i.e. your system to a particular PORT at a particular IP so that they can communicate to each other.
    • AF_INET is an address family used to accept IP of address type v4 as a parameter to which the defined socket will communicate
    • SOCK_STREAM is a connection-based protocol, in this program using TCP(transmission control protocol) is used to accept a port no. as a parameter

calculate_time():

Unavailability time is the time duration for which the internet connection was unavailable. is calculated using downtime(stop) time when the internet connection got lost and uptime(start) time when the internet connection got restored

Python




def calculate_time(start, stop):
   
    # to calculate unavailability time
    difference = stop - start
    seconds = float(str(difference.total_seconds()))
    return str(datetime.timedelta(seconds=seconds)).split(".")[0]


first_check():

This function will only be executed once, i.e. at the beginning of the script to check if the system is already connected to an internet connection or not, and write that into the log file. ping() function is called

  1. If ping returns true(machine is connected to the internet), the script will print “CONNECTION ACQUIRED” and write the same into the log file.
  2. If ping returns false(the system is not connected to the internet), the script will print “CONNECTION NOT ACQUIRED” and write the same into the log file.

Python




def first_check():
    # to check if the machine already have a live internet connection
 
    # if ping returns true
    if ping():
        live = "\nCONNECTION ACQUIRED\n"
        print(live)
        connection_acquired_time = datetime.datetime.now()
        acquiring_message = "connection acquired at: " + \
            str(connection_acquired_time).split(".")[0]
        print(acquiring_message)
 
        # writes into the log file
        with open(FILE, "a") as file:
            file.write(live)
            file.write(acquiring_message)
        return True
 
    # if ping returns false
    else:
        not_live = "\nCONNECTION NOT ACQUIRED\n"
        print(not_live)
 
        # writes into the log file
        with open(FILE, "a") as file:
            file.write(not_live)
        return False


main():

The main function, where all the user-defined programs will be executed and the live internet status will be written into a log file.

Python




def main():
    # MAIN
    monitor_start_time = datetime.datetime.now()
     
    # monitoring time is when the script
    # started monitoring internet connection status
    monitoring_date_time = "monitoring started at: " + \
        str(monitor_start_time).split(".")[0]
 
    if first_check():
        # if true
        print(monitoring_date_time)
         
        # monitoring will only start when
        # the connection will be acquired
 
    else:
        # if false
        while True:
           
            # infinite loop to check if the connection is acquired
            # will run until there is a live internet connection
            if not ping():
               
                # if connection not acquired
                time.sleep(1)
            else:
               
                # if connection is acquired
                first_check()
                print(monitoring_date_time)
                break
 
            with open(FILE, "a") as file:
                # writes into the log file
                file.write("\n")
                file.write(monitoring_date_time + "\n")
 
    while True:
       
        # FIRST WHILE, infinite loop,
        # will run until the machine is on
        # or the script is manually terminated
        if ping():
            # if true: the loop will execute after every 5 seconds
            time.sleep(5)
 
        else:
           
            # if false: fail message will be displayed
            down_time = datetime.datetime.now()
            fail_msg = "disconnected at: " + str(down_time).split(".")[0]
            print(fail_msg)
 
            with open(FILE, "a") as file:
                # writes into the log file
                file.write(fail_msg + "\n")
 
            while not ping():
                # infinite loop,
                # will run till ping() return true
                time.sleep(1)
 
            up_time = datetime.datetime.now()
             
            # will execute after while true is
            # false (connection restored)
            uptime_message = "connected again: " + str(up_time).split(".")[0]
 
            down_time = calculate_time(down_time, up_time)
             
            # calling time calculating
            # function, printing down time
            unavailablity_time = "connection was unavailable for: " + down_time
 
            print(uptime_message)
            print(unavailablity_time)
 
            with open(FILE, "a") as file:
                 
                # log entry for connected restoration time,
                # and unavailability time
                file.write(uptime_message + "\n")
                file.write(unavailablity_time + "\n")


Explanation:

  • First, first_check() will be executed (this function will be executed only one time, i.e. at the beginning of the script)
    1. If true(connection acquired): monitoring will start
    2. If false(connection not acquired): else statement will be executed having infinite while loop to check for the internet connection using ping() function
      1. If ping will return false, the loop will be executed after every second until the ping() function returns true
      2. If ping will return true(connection acquired), the loop will break, and monitoring will be started
  • Second, to monitor the network connection, the first while statement will be executed, which is an infinite loop
    1. If ping returns true, the loop will be executed after every 5 seconds until it returns false
    2. If ping returns false, downtime will be printed, and the loop will execute after every second until an internet connection is restored
    3. After internet connection is restored, uptime and unavailability time will be printed, and iteration will get back to the start of the loop

Flow chart:

Below is the implementation:

Python




import os
import sys
import socket
import datetime
import time
 
 
FILE = os.path.join(os.getcwd(), "networkinfo.log")
 
# creating log file in the currenty directory
# ??getcwd?? get current directory,
# os function, ??path?? to specify path
 
 
def ping():
    # to ping a particular IP
    try:
        socket.setdefaulttimeout(3)
         
        # if data interruption occurs for 3
        # seconds, <except> part will be executed
 
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # AF_INET: address family
        # SOCK_STREAM: type for TCP
 
        host = "8.8.8.8"
        port = 53
 
        server_address = (host, port)
        s.connect(server_address)
 
    except OSError as error:
        return False
        # function returns false value
        # after data interruption
 
    else:
        s.close()
        # closing the connection after the
        # communication with the server is completed
        return True
 
 
def calculate_time(start, stop):
   
    # calculating unavailability
    # time and converting it in seconds
    difference = stop - start
    seconds = float(str(difference.total_seconds()))
    return str(datetime.timedelta(seconds=seconds)).split(".")[0]
 
 
def first_check():
    # to check if the system was already
    # connected to an internet connection
 
    if ping():
        # if ping returns true
        live = "\nCONNECTION ACQUIRED\n"
        print(live)
        connection_acquired_time = datetime.datetime.now()
        acquiring_message = "connection acquired at: " + \
            str(connection_acquired_time).split(".")[0]
        print(acquiring_message)
 
        with open(FILE, "a") as file:
           
            # writes into the log file
            file.write(live)
            file.write(acquiring_message)
 
        return True
 
    else:
        # if ping returns false
        not_live = "\nCONNECTION NOT ACQUIRED\n"
        print(not_live)
 
        with open(FILE, "a") as file:
           
            # writes into the log file
            file.write(not_live)
        return False
 
 
def main():
   
    # main function to call functions
    monitor_start_time = datetime.datetime.now()
    monitoring_date_time = "monitoring started at: " + \
        str(monitor_start_time).split(".")[0]
 
    if first_check():
        # if true
        print(monitoring_date_time)
        # monitoring will only start when
        # the connection will be acquired
 
    else:
        # if false
        while True:
           
            # infinite loop to see if the connection is acquired
            if not ping():
                 
                # if connection not acquired
                time.sleep(1)
            else:
                 
                # if connection is acquired
                first_check()
                print(monitoring_date_time)
                break
 
    with open(FILE, "a") as file:
       
        # write into the file as a into networkinfo.log,
        # "a" - append: opens file for appending,
        # creates the file if it does not exist???
        file.write("\n")
        file.write(monitoring_date_time + "\n")
 
    while True:
       
        # infinite loop, as we are monitoring
        # the network connection till the machine runs
        if ping():
             
            # if true: the loop will execute after every 5 seconds
            time.sleep(5)
 
        else:
            # if false: fail message will be displayed
            down_time = datetime.datetime.now()
            fail_msg = "disconnected at: " + str(down_time).split(".")[0]
            print(fail_msg)
 
            with open(FILE, "a") as file:
                # writes into the log file
                file.write(fail_msg + "\n")
 
            while not ping():
               
                # infinite loop, will run till ping() return true
                time.sleep(1)
 
            up_time = datetime.datetime.now()
             
            # after loop breaks, connection restored
            uptime_message = "connected again: " + str(up_time).split(".")[0]
 
            down_time = calculate_time(down_time, up_time)
            unavailablity_time = "connection was unavailable for: " + down_time
 
            print(uptime_message)
            print(unavailablity_time)
 
            with open(FILE, "a") as file:
                 
                # log entry for connection restoration time,
                # and unavailability time
                file.write(uptime_message + "\n")
                file.write(unavailablity_time + "\n")
 
main()


Output:

CONNECTION ACQUIRED

connection acquired at: 2021-09-16 15:03:18
monitoring started at: 2021-09-16 15:03:18
disconnected at: 2021-09-16 15:03:49
connected again: 2021-09-16 15:03:50
connection was unavailable for: 0:00:01


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads