Build a Network Ping Monitor in Python
A Python script that continuously pings a remote host using subprocess and reports connectivity status with timestamps and latency.
Python code
38 linesimport subprocess
import time
def ping_host(host, count=4):
"""Ping a host and return the results."""
try:
# Platform-independent ping command
cmd = ["ping", "-c", str(count), host]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
return result.stdout, result.returncode
except subprocess.TimeoutExpired:
return "Ping timed out", 1
except FileNotFoundError:
return "Ping command not found", 1
def monitor_host(host, interval=5, pings_per_check=3):
"""Monitor network connectivity to a host."""
print(f"Monitoring {host} every {interval} seconds...")
try:
while True:
output, return_code = ping_host(host, pings_per_check)
timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
if return_code == 0:
# Extract latency from ping output
latency_line = [line for line in output.split('\n')
if 'time=' in line or 'time<' in line]
print(f"[{timestamp}] ✓ {host} is reachable | {latency_line[-1] if latency_line else 'OK'}")
else:
print(f"[{timestamp}] ✗ {host} is NOT reachable")
time.sleep(interval)
except KeyboardInterrupt:
print("\nMonitoring stopped by user")
if __name__ == "__main__":
# Monitor Google DNS for demonstration
monitor_host("8.8.8.8", interval=3, pings_per_check=2)
Output
Monitoring 8.8.8.8 every 3 seconds...
[2025-01-15 14:32:10] ✓ 8.8.8.8 is reachable | time=12.3 ms
[2025-01-15 14:32:13] ✓ 8.8.8.8 is reachable | time=11.8 ms
[2025-01-15 14:32:16] ✗ 8.8.8.8 is NOT reachable
^C
Monitoring stopped by user
How it works
The script uses subprocess.run to execute the system ping command with -c to limit the number of pings. It captures stdout and the return code — zero means success. Latency is extracted from lines containing time= using a list comprehension and string slicing. A while True loop with time.sleep runs indefinitely until a KeyboardInterrupt stops it gracefully. The FileNotFoundError and TimeoutExpired exceptions handle missing ping binary or slow responses.
Common mistakes
- Using `ping` without the `-c` flag, causing infinite pinging on some platforms.
- Not wrapping the loop in a `try/except KeyboardInterrupt` to stop cleanly.
- Assuming ping output format is identical across all operating systems (e.g., Windows uses different strings).
- Forgetting to set a timeout on `subprocess.run`, which can block the monitor forever.
Variations
- Use `platform.system()` to adapt ping arguments for Windows (`-n` instead of `-c`).
- Log results to a file using Python's logging module instead of printing to stdout.
- Send an email or Slack alert when connectivity is lost using `smtplib` or `requests`.
Real-world use cases
- Monitoring VPN tunnel stability and logging intermittent drops for troubleshooting.
- Checking if a local server is reachable on the network before launching a dependent service.
- Running as a background health-check script that triggers alerts when latency spikes above a threshold.
Sponsored
More from Automation & scripting
- Batch Rename Hundreds of Files in Python easy
- Build a Command-Line Password Generator in Python easy
- Build a Complete Web Scraper with Requests and BeautifulSoup in Python medium
- Create a Local Search Engine to Instantly Find Files on Your Computer in Python medium
- Create a Simple HTTP File Server in Python easy
- Detect and Remove Blurry Images in Python with OpenCV medium
Keep learning
Related tutorials and quizzes for this topic.