Pinging servers in Python

2019-01-02 20:12发布

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?

24条回答
一个人的天荒地老
2楼-- · 2019-01-02 20:37

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 by subprocess.call.

from platform   import system as system_name  # Returns the system/OS name
from subprocess import call   as system_call  # Execute a shell command

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Ping command count option as function of OS
    param = '-n' if system_name().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]

    # Pinging
    return system_call(command) == 0

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 macOS
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l'])

查看更多
泛滥B
3楼-- · 2019-01-02 20:39

There is a module called pyping that can do this. It can be installed with pip

pip install pyping

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.

import pyping

r = pyping.ping('google.com')

if r.ret_code == 0:
    print("Success")
else:
    print("Failed with {}".format(r.ret_code))
查看更多
萌妹纸的霸气范
4楼-- · 2019-01-02 20:39

Make Sure pyping is installed or install it pip install pyping

#!/usr/bin/python
import pyping

response = pyping.ping('Your IP')

if response.ret_code == 0:
    print("reachable")
else:
    print("unreachable")
查看更多
若你有天会懂
5楼-- · 2019-01-02 20:39

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:

from easyprocess import EasyProcess # as root: pip install EasyProcess
def ping(ip):
    ping="ssh %s date;exit"%(ip) # test ssh alive or
    ping="curl -IL %s"%(ip)      # test if http alive
    response=len(EasyProcess(ping).call(timeout=2).stdout)
    return response #integer 0 if no response in 2 seconds
查看更多
骚的不知所云
6楼-- · 2019-01-02 20:40
#!/usr/bin/python3

import subprocess as sp

ip = "192.168.122.60"
status,result = sp.getstatusoutput("ping -c1 -w2 " + ip)

if status == 0: 
    print("System " + ip + " is UP !")
else:
    print("System " + ip + " is DOWN !")
查看更多
看淡一切
7楼-- · 2019-01-02 20:41

Using Multi-ping (pip install multiPing) I made this simple code (simply copy and paste if you will!):

from multiping import MultiPing

def ping(host,n = 0):
    if(n>0):
        avg = 0
        for i in range (n):
            avg += ping(host)
        avg = avg/n
    # Create a MultiPing object to test hosts / addresses
    mp = MultiPing([host])

    # Send the pings to those addresses
    mp.send()

    # With a 1 second timout, wait for responses (may return sooner if all
    # results are received).
    responses, no_responses = mp.receive(1)


    for addr, rtt in responses.items():
        RTT = rtt


    if no_responses:
        # Sending pings once more, but just to those addresses that have not
        # responded, yet.
        mp.send()
        responses, no_responses = mp.receive(1)
        RTT = -1

    return RTT

Usage:

#Getting the latency average (in seconds) of host '192.168.0.123' using 10 samples
ping('192.168.0.123',10)

If you want a single sample, the second parameter "10" can be ignored!

Hope it helps!

查看更多
登录 后发表回答