In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Django __str__ returned non-string (type NoneType)
- Evil ctypes hack in python
This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3
EDIT 1: Added some comments to the original answer.
EDIT 2: Following a suggestion by @radato,
os.system
was replaced bysubprocess.call
.The command is
ping
in both Windows and Unix-like systems. The option -n (Windows) or -c (Unix) controls the number of packets which in this example is 1.platform.system()
returns the platform name. Ex.'Darwin'
in macOSsubprocess.call()
performs a system call. Ex.subprocess.call(['ls','-l'])
There is a module called pyping that can do this. It can be installed with pip
It is pretty simple to use, however, when using this module, you need root access due to the fact that it is crafting raw packets under the hood.
Make Sure pyping is installed or install it pip install pyping
Seems simple enough, but gave me fits. I kept getting "icmp open socket operation not permitted" or else the solutions would hang up if the server was off line. If, however, what you want to know is that the server is alive and you are running a web server on that server, then curl will do the job. If you have ssh and certificates, then ssh and a simple command will suffice. Here is the code:
Using Multi-ping (
pip install multiPing
) I made this simple code (simply copy and paste if you will!):Usage:
If you want a single sample, the second parameter "
10
" can be ignored!Hope it helps!