Monitoring an Internet Connection using Python

When RaspberryPi 3+ first came out after playing with sensors and an Arduino Uno board for a while, I used it for monitoring wireless and internet connections in different premises. Thanks to the compact size and the low power needed it was the best tool.  I thought it would be interesting to know how consistent was the available bandwidth was during the day and eventually know if there were some unnoticed outages happening.

During these years I’ve used similar utilities, but I decided to write and share with you a simpler script that could be implemented quickly and help you to achieve similar results regardless that you run it inside a docker container, virtual machine or raspberry pi.

Without re-inventing the wheel I’ve used Speedtest CLI, knowing that most likely it would be for many of us the first tool to run to test an internet connection.  Speedtest CLI

Install speedtest-cli

https://pypi.org/project/speedtest-cli/

Check the version

You can use the speedtest cli from bash to output JSON (speedtest –json) or CSV (speedtests –csv).

Running a simple speedtest

How to simulate a file transfer using the single connection option

Testing with multiple connections is useful to ‘stress’ the link and if you want to know what is the full potential, but it’s not a good estimate for a file transfer, in that regards it’s better to use the —single option and if you want to know the bandwidth values in byte instead of bit you can also use –byte.

JSON And CSV outputs and other options

For more options check the –help and the GitHub repository of the maintainer Matt Martz (https://github.com/sivel/speedtest-cli)

My Python Script

I’ve used F Strings and Format String both in that script to let you show the options that the Python language offers to you.

Change the permissions on your script:

create a log file and set relaxed permissions accordingly

For scheduling your script you can use crontab.guru to double-check your crontab syntax.

Scheduling your script

I generally run this test every hour, but for this specific script, I ran it every 5 minutes.

Use crontab to schedule the execution of your python script every 5 minutes

or simply

Checking the log file

tail-ing “speedtest.log” to get the last 5 tests completed during the last 25 minutes (5x5minutes).

I hope you will find it useful! As usual, you can find this script on my Github repository.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.