Python Script to Monitor Network Connection and saving into Log File
Last Updated :
23 Feb, 2022
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).
- The system will try pinging a specific server(PORT at an IP)
- If the machine fails to connect, EXCEPT statement will be executed
- 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
- If ping returns true(machine is connected to the internet), the script will print "CONNECTION ACQUIRED" and write the same into the log file.
- 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)
- If true(connection acquired): monitoring will start
- If false(connection not acquired): else statement will be executed having infinite while loop to check for the internet connection using ping() function
- If ping will return false, the loop will be executed after every second until the ping() function returns true
- 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
- If ping returns true, the loop will be executed after every 5 seconds until it returns false
- If ping returns false, downtime will be printed, and the loop will execute after every second until an internet connection is restored
- 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
Similar Reads
How to check any script is running in linux using Python?
Python is a strong and exponentially growing programming language in the present day. There is a multiple-way to check which script is running in the background of a Linux environment. One of them is using the subprocess module in python. Subprocess is used to run new programs through Python code by
2 min read
How to Log Python Messages to Both stdout and Files
Python Loggers are essential tools for tracking and debugging applications, allowing developers to record messages of various severity levels. By configuring loggers to output messages to both stdout and log files, developers can ensure real-time monitoring and persistent storage of logs for later a
2 min read
View Computer's Important Network Information Using Python
While working in a network, we do some troubleshooting with the network or Internet problem. This time we need to check your own system network connection information. We can find the network connection in the Control Panel in Windows. The best way to find this information we can use ipconfig comman
1 min read
Access files of a devices in the same network using Python
We have so many ways to Transfer Files from one computer to another in Linux and Ubuntu but there we have to change the permissions of the Apache Folder and then Share the files. But in windows, we cannot share files using Apache so here we have discussed Python Method to Share files between Systems
2 min read
How to Disconnect Devices from Wi-Fi using Scapy in Python?
Without permission, disconnecting a device from a Wi-Fi network is against the law and immoral. Sometimes, you might need to check your network's security or address network problems. You may send a de-authentication packet to disconnect devices from Wi-Fi using Scapy, a potent Python packet manipul
5 min read
Python | Add Logging to a Python Script
In this article, we will learn how to have scripts and simple programs to write diagnostic information to log files. Code #1 : Using the logging module to add logging to a simple program Python3 1== import logging def main(): # Configure the logging system logging.basicConfig(filename ='app.log', le
2 min read
Scraping data in network traffic using Python
In this article, we will learn how to scrap data in network traffic using Python. Modules Neededselenium: Selenium is a portable framework for controlling web browser.time: This module provides various time-related functions.json: This module is required to work with JSON data.browsermobproxy: This
5 min read
Network Scanning using scapy module - Python
Scapy is a library supported by both Python2 and Python3. It is used for interacting with the packets on the network. It has several functionalities through which we can easily forge and manipulate the packet. Through scapy module we can create different network tools like ARP Spoofer, Network Scann
3 min read
How to find available WiFi networks using Python?
WiFi (Wireless Fidelity) is a wireless technology that allows devices such as computers (laptops and desktops), mobile devices (smartphones and wearables), and other equipment (printers and video cameras) to interface with the Internet. We can find out the names of the WiFi names with the help of Py
2 min read
An application to test the given page is found or not on the server using Python
Prerequisite: Python Urllib module In this article, we are going to write scripts to test whether the given page is found on the server or not with a GUI application. We need to Install Urllib Module to carry out this operation. Type this command in your terminal. pip install urllib Approach: Import
2 min read