The Palos Publishing Company

Follow Us On The X Platform @PalosPublishing
Categories We Write About

Monitor your internet speed with Python

Monitoring internet speed using Python is a practical task that can be automated with simple scripts. It allows users to keep track of their download, upload, and ping rates over time. This can be especially useful for identifying connectivity issues, verifying ISP claims, or logging speed data for performance analysis.

Required Libraries

To create a functional internet speed monitoring tool, Python offers several libraries that make the task efficient:

  • speedtest-cli: A command-line interface for testing internet bandwidth using speedtest.net.

  • datetime: Used to log timestamps.

  • csv: To store speed test data in a structured file format.

  • schedule and time: To automate periodic checks.

Install necessary libraries with:

bash
pip install speedtest-cli schedule

Building the Speed Monitor

Below is a complete Python script to monitor and log internet speed.

python
import speedtest import csv from datetime import datetime import schedule import time def test_speed(): try: st = speedtest.Speedtest() st.get_best_server() download_speed = st.download() / 1_000_000 # Convert from bits to Mbps upload_speed = st.upload() / 1_000_000 ping_result = st.results.ping timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') print(f"{timestamp} | Download: {download_speed:.2f} Mbps | Upload: {upload_speed:.2f} Mbps | Ping: {ping_result:.2f} ms") with open("internet_speed_log.csv", mode="a", newline="") as file: writer = csv.writer(file) writer.writerow([timestamp, f"{download_speed:.2f}", f"{upload_speed:.2f}", f"{ping_result:.2f}"]) except Exception as e: print(f"Error while testing speed: {e}") # Log every 30 minutes schedule.every(30).minutes.do(test_speed) # Initialize CSV if it doesn't exist try: with open("internet_speed_log.csv", mode="x", newline="") as file: writer = csv.writer(file) writer.writerow(["Timestamp", "Download (Mbps)", "Upload (Mbps)", "Ping (ms)"]) except FileExistsError: pass print("Starting internet speed monitoring...") test_speed() while True: schedule.run_pending() time.sleep(1)

Understanding the Output

The script records three primary metrics:

  • Download Speed: Measures how fast data is received from the internet.

  • Upload Speed: Indicates the speed at which data is sent to the internet.

  • Ping: Reflects the network latency in milliseconds, representing the time taken for a packet to travel to the server and back.

The results are printed on the console and also saved in a CSV file named internet_speed_log.csv for historical tracking and analysis.

Analyzing the Data

Over time, the CSV log can be analyzed using tools like Excel, Google Sheets, or Python libraries such as pandas and matplotlib. Here’s a sample script to generate a simple graph of the speed trends:

python
import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv("internet_speed_log.csv", parse_dates=["Timestamp"]) plt.figure(figsize=(10, 6)) plt.plot(df["Timestamp"], df["Download (Mbps)"], label="Download Speed") plt.plot(df["Timestamp"], df["Upload (Mbps)"], label="Upload Speed") plt.xlabel("Timestamp") plt.ylabel("Speed (Mbps)") plt.title("Internet Speed Over Time") plt.legend() plt.xticks(rotation=45) plt.tight_layout() plt.show()

This visualization allows users to identify patterns such as slowdowns during peak hours or network stability issues.

Advanced Features

To extend the functionality, you can consider:

  • Sending Alerts: Integrate email or SMS alerts when speed drops below a defined threshold.

  • Web Dashboard: Use Flask or Django to create a web-based dashboard.

  • Database Integration: Store logs in a database like SQLite, PostgreSQL, or MongoDB for advanced querying and reporting.

Example: Speed Drop Email Notification

python
import smtplib from email.message import EmailMessage def send_alert(download_speed, upload_speed): if download_speed < 10 or upload_speed < 2: msg = EmailMessage() msg.set_content(f"Low internet speed detected!nDownload: {download_speed} MbpsnUpload: {upload_speed} Mbps") msg['Subject'] = 'Internet Speed Alert' msg['From'] = 'your_email@example.com' msg['To'] = 'recipient@example.com' try: with smtplib.SMTP('smtp.gmail.com', 587) as server: server.starttls() server.login('your_email@example.com', 'your_password') server.send_message(msg) print("Alert email sent.") except Exception as e: print(f"Failed to send email: {e}")

This function can be triggered inside the test_speed() function based on speed thresholds.

Use Cases

  1. ISP Monitoring: Verify if your internet provider is delivering promised speeds.

  2. Remote Work Support: Ensure consistent speeds during working hours.

  3. IoT Device Management: Monitor connectivity for smart devices.

  4. Data-Driven Troubleshooting: Identify trends before contacting support.

Deployment Options

  • Raspberry Pi: Deploy the script on a Raspberry Pi for continuous background monitoring.

  • Cron Jobs: Instead of schedule, use OS-level task schedulers for more control.

  • Docker Container: Package the script into a container for isolated and portable execution.

Conclusion

Monitoring internet speed with Python is a powerful method to gather insights about your network performance. Using simple libraries like speedtest-cli and schedule, you can automate periodic tests, log data for long-term trends, and even set up real-time alerts. Whether for personal use or professional analysis, this Python-based approach provides transparency and control over your internet connectivity.

Share this Page your favorite way: Click any app below to share.

Enter your email below to join The Palos Publishing Company Email List

We respect your email privacy

Categories We Write About