Using Python to Monitor ISP Connectivity

At home my internet modem occasionally loses connectivity with the web. I can see other devices on the network, so I’m sure it is not the modem that has gone down completely. It is somewhere between my modem and my ISP. The weird thing about the web connectivity outages is they seem to all happen exactly at midnight. The frequent drops are a bit of a headache, and I want to see if I can establish a concrete pattern of outages. I decided to write a Python utility for programmatically monitoring connectivity even when I’m not at home and online. ‘ping’ is an easy way to continuously check a connection, but I wanted something more robust. Here is how to do it:

In your favorite python editor, the first thing you will need to do is import the necessary packages:

import socket # For attempting to connect to a web site.
import datetime # For timestamps.
from time import sleep # Reduce web site request frequency. Play nice.

Let’s create a function for creating timestamps in a human-readable format for our logs:
def timestamp():
     return datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

And a function for connecting to a web site.
def connect_to_url(url="www.google.com"):
     try:
          socket.create_connection((url, 80))
          return timestamp(), "OK"
     except OSError:
          pass
     return timestamp(), "FAIL"

The above example uses google.com as the default, but you can override that by passing in your own url argument when calling the connect_to_url( ) function.

Finally, let’s create a main method so the script will not execute when the python file is imported by other scripts:

if __name__ == "__main__":
     while True: # Infinite loop.
          ts, status = connect_to_url()
          print(ts, status)
          sleep(5)

Now you can run the script from the command line. Say your script is named isp_qos.py, all you need to do from the command line is type: python ios_qos.py

In a follow-up post, I will show how to add in a data store to save the time series for tracking track trends.