Maintenance

Site is under maintenance — quizzes are still available.

Go to quizzes
Sponsored Reserved space — layout preview until AdSense is connected

Track Internet Connectivity and Downtime Automatically in Python

Monitors internet connectivity by pinging a remote host and logs any downtime events with timestamps and duration.

Medium Python 3.9+ Jun 28, 2026 Automation & scripting 2 views 0 copies

Python code

51 lines
Python 3.9+
import time
import subprocess
from datetime import datetime

def check_internet(host="8.8.8.8", timeout=3):
    """Returns True if internet is reachable via ping."""
    try:
        subprocess.run(
            ["ping", "-c", "1", "-W", str(timeout), host],
            capture_output=True,
            timeout=timeout + 2
        )
        return True
    except (subprocess.TimeoutExpired, subprocess.CalledProcessError, FileNotFoundError):
        return False

def track_connectivity(interval=5, max_downtime_logs=10):
    """Monitors internet connectivity and logs downtime."""
    downtime_start = None
    downtime_events = []

    print(f"Tracking internet connectivity every {interval} seconds...")
    print("Press Ctrl+C to stop.\n")

    try:
        while len(downtime_events) < max_downtime_logs:
            if check_internet():
                if downtime_start:
                    duration = time.time() - downtime_start
                    downtime_events.append((downtime_start, duration))
                    dt = datetime.fromtimestamp(downtime_start).isoformat()
                    print(f"Recovered at {datetime.now().isoformat()} after {duration:.1f}s downtime (started {dt})")
                    downtime_start = None
            else:
                if not downtime_start:
                    downtime_start = time.time()
                    print(f"Lost internet at {datetime.now().isoformat()}")
            time.sleep(interval)
    except KeyboardInterrupt:
        print("\nTracking stopped by user.")

    if downtime_events:
        print("\nDowntime Summary:")
        for start, duration in downtime_events:
            dt = datetime.fromtimestamp(start).isoformat()
            print(f"  Started: {dt}, Duration: {duration:.1f}s")
    else:
        print("\nNo downtime detected during tracking period.")

if __name__ == "__main__":
    track_connectivity(interval=2, max_downtime_logs=3)

Output

stdout
Tracking internet connectivity every 2 seconds...
Press Ctrl+C to stop.

Lost internet at 2025-03-28T10:15:30.123456
Recovered at 2025-03-28T10:15:35.654321 after 5.0s downtime (started 2025-03-28T10:15:30.123456)
Lost internet at 2025-03-28T10:15:40.789012

Downtime Summary:
  Started: 2025-03-28T10:15:30.123456, Duration: 5.0s

How it works

The check_internet function uses subprocess.run to execute a single ping (-c 1) to a stable host (Google DNS 8.8.8.8) with a timeout. If the ping fails (timeout, non-zero exit, or command not found), it returns False. The track_connectivity loop calls this function every interval seconds. When a failure is detected, it records the timestamp of the start of downtime. Once connectivity resumes, it calculates the duration and logs the event. The loop stops after a user-defined maximum number of downtime events or when interrupted with Ctrl+C, then prints a summary of all downtime periods.

Common mistakes

  • Using `ping -n` on Windows instead of `-c`; the code as written is Linux/macOS specific but can be adapted with platform detection.
  • Setting the ping timeout too short causing false positives for slow connections.
  • Not catching `FileNotFoundError` when the `ping` command is not installed.

Variations

  1. Use `requests.get('http://httpstat.us/200', timeout=3)` instead of ping for a more application-level check.
  2. Use `socket.create_connection(('8.8.8.8', 53), timeout=3)` to test DNS reachability without external dependencies.

Real-world use cases

  • Running as a background script on a server to log intermittent network outages for ISP diagnosis.
  • Integrating into a home automation system to trigger alerts when internet drops.
  • Collecting connectivity metrics in a small embedded device to report uptime statistics.

Sponsored

Sponsored Reserved space — layout preview until AdSense is connected

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.