< All posts

March 1, 2020, 8:28 p.m.

PythonPing to determine if Router is Up

We can use ping to determine whether a host is up or down, in my case I use it to determine whether a power failure has occurred. I needed a script to automatically ping my router and if it does not respond, it will trigger something like an automated emergency shutdown of my server. To do this using python, I researched on a package from the net.

PythonPing - A simple way to ping in Python

I found this PythonPing, it is a simple python package that allows you to ping using python (hence the name), but your script must run with root privileges.

Install pythonping package as root

$ sudo python3 -m pip install  pythonping
Looking in indexes: https://pypi.org/simple, https://www.piwheels.org/simple
Collecting pythonping
  Downloading https://www.piwheels.org/simple/pythonping/pythonping-1.0.8-py3-none-any.whl (11 kB)
Installing collected packages: pythonping
Successfully installed pythonping-1.0.8

Script to check if router is pingable, return true if yes.

#!/usr/bin/python

from pythonping import ping
import time

routerA = ping('172.16.1.1')
isAliveA = str(routerA._responses[0].success)

print(str(time.ctime(time.time())))
if (isAliveA == "False"):
    print("ROUTER A FAIL")
else:
    print("ROUTER A OK")

Sample output:

$ sudo python3 ./ping.py
Sun Mar  1 20:15:58 2020
ROUTER A OK

References:
https://github.com/alessandromaggio/pythonping
https://github.com/alessandromaggio/pythonping/issues/16