Python library to send pings that doesn't require elevated permissions?

77 Views Asked by At

I am writing a python 3 script and I need to implement a function where I ping a server to see if it is reachable. The only thing is I have the following constraints

  • Cannot use subprocess as everything should be contained within Python.
  • Cannot use common ping libraries like icmplib , ping3 , etc as they require the script to run with elevated privileges.

Does such a library exist for python3 ? Or is there another way to implement this ?

I have tried using the following libraries , icmplib , ping3 , pingparsing and a handful of others but they require elevated privileges to send icmp packets and in my scenario that is not an option.

1

There are 1 best solutions below

0
J_H On

We require that the server shall be listening on at least one TCP port, such as {80, 443, 22).

Use requests to connect to that port. If TCP 3-way handshake completes promptly, the server is reachable. If it quickly rejects the attempt, likely it is reachable but not currently listening on that port, for example because it recently rebooted and nginx has not yet restarted.

Consider creating a small HTML document on the server, and then client does a GET of http://example.com/health.html, declaring "reachable!" upon receiving a 200 status.


One could implement a similar approach over UDP, but it tends to be less convenient. Running a caching nameserver on UDP port 53 would let a dig client interrogate the server at low cost. Pypi offers more than one DNS client library which can issue such queries.

Deliberately contacting the server's kernel with requests on an unused port, such as 81, might hold some charm. It would elevate certain error counters which typically remain much closer to zero.


There is more than one way to execute this command, which never exits:

$ ping -i10 server.example.com  >> /tmp/ping.log

For example, we could accomplish that with check_call(), or via some external daemon.

With that in place, it is straightforward for python to repeatedly stat() the log file and essentially tail -f its results using seek(), to report failure as soon as there is a missed ping response.