Network connectivity monitoring script: Alert failed pings only (Python script)

Published on January 5th, 2025

Monitoring network connectivity can be crucial when investigating an intermittent issue. This article aims to share a simple Python script to monitor network connectivity using the ping command on either Windows or Linux operating systems.

The script continuously pings a specified host and logs any connectivity failures, all while maintaining compatibility across different operating systems.

Prerequisites

Before diving into the script, ensure you have the following:

  • Python installed on your system (Python 3.6 or later is recommended)
  • Basic knowledge of programming

The script

Here’s the complete Python script:

# This script pings a host on a fixed frequency (defaulted to 5 seconds) and only reports if a ping fails. This is useful for monitoring the stability of a connection without needing to scroll through successful pings for failed ones.

# --------------
# Configuration
# --------------
# - Target host: Change the first parameter on the final line if you are monitoring a specific host. This is initially set to Google's DNS service at 8.8.8.8 to monitor Internet connectivity of the device running this script.
# - Frequency: Change the second parameter on the final line if you require a different frequency. This is initially set to 5 seconds between pings.

import subprocess
import time
from datetime import datetime
import platform

def attempt_ping(host):
    # Check the operating system (Windows ping uses -n to set ping count, Linux uses -c)
    param = '-n' if platform.system().lower() == 'windows' else '-c'
    
    # Send one ping to the host
    #   stdout and stderr values of subprocess.DEVNULL hide the ping command output so this script handles all output
    result = subprocess.run(['ping', param, '1', host], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    return result.returncode

def monitor_host(host, interval=5):
    while True:
        if attempt_ping(host) != 0:
            timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            print(f"{timestamp} - Failed to reach {host}")
        time.sleep(interval)

if __name__ == "__main__":
    monitor_host("8.8.8.8", 5)

Explanation

Let’s break down the script step-by-step:

  1. Importing modules: We start by importing necessary modules:
    • subprocess for running external commands (in this case, ping)
    • time for adding delays between pings
    • datetime for timestamping outputs
    • platform for detecting the operating system (needed to use the appropriate ping parameters)
  2. Ping function: The attempt_ping function sends a single ping to the specified host. It first checks the operating system using platform.system(). If the OS is Windows, it uses the -n parameter; otherwise, it uses -c (common to Unix-like systems including Linux). The ping command’s output is suppressed by redirecting stdout and stderr to subprocess.DEVNULL.
  3. Monitor function: The monitor_host function continuously pings the host at specified intervals (default is 5 seconds). If a ping fails, it logs the timestamp and the failure message. The script runs in an infinite loop, using time.sleep(interval) to wait between pings.
  4. Main function: The script starts execution from the if __name__ == "__main__": block, calling the monitor_host function with the target host “8.8.8.8” (Google’s public DNS server).

Usage

  1. Save the script as monitor_network.py.
  2. Open a terminal or command prompt and navigate to the directory where the script is saved.
  3. Run the script with the command: python monitor_network.py.

The script will start pinging the specified host and print messages if it fails to reach the host, providing a timestamp for each failure. Please note, there is no output if the ping is successful, this deliberate to avoid “noise” in the output when monitoring. If you want to see successful pings too, you can adjust the script or simply call the ping command directly.

Happy monitoring!

Adblocker detected

Please bear in mind that ad blockers prevent this website covering its costs.

If you find this site useful, please consider supporting me by whitelisting this site, or making a £1 / $1 donation.