Ping a site in Python?

前端 未结 15 2247
我寻月下人不归
我寻月下人不归 2020-11-22 09:22

How do I ping a website or IP address with Python?

相关标签:
15条回答
  • 2020-11-22 09:44

    Depending on what you want to achive, you are probably easiest calling the system ping command..

    Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!

    import subprocess
    
    host = "www.google.com"
    
    ping = subprocess.Popen(
        ["ping", "-c", "4", host],
        stdout = subprocess.PIPE,
        stderr = subprocess.PIPE
    )
    
    out, error = ping.communicate()
    print out
    

    You don't need to worry about shell-escape characters. For example..

    host = "google.com; `echo test`
    

    ..will not execute the echo command.

    Now, to actually get the ping results, you could parse the out variable. Example output:

    round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms
    

    Example regex:

    import re
    matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
    print matcher.search(out).groups()
    
    # ('248.139', '249.474', '250.530', '0.896')
    

    Again, remember the output will vary depending on operating system (and even the version of ping). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)

    0 讨论(0)
  • 2020-11-22 09:44

    You can find an updated version of the mentioned script that works on both Windows and Linux here

    0 讨论(0)
  • 2020-11-22 09:46

    using system ping command to ping a list of hosts:

    import re
    from subprocess import Popen, PIPE
    from threading import Thread
    
    
    class Pinger(object):
        def __init__(self, hosts):
            for host in hosts:
                pa = PingAgent(host)
                pa.start()
    
    class PingAgent(Thread):
        def __init__(self, host):
            Thread.__init__(self)        
            self.host = host
    
        def run(self):
            p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
            m = re.search('Average = (.*)ms', p.stdout.read())
            if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
            else: print 'Error: Invalid Response -', self.host
    
    
    if __name__ == '__main__':
        hosts = [
            'www.pylot.org',
            'www.goldb.org',
            'www.google.com',
            'www.yahoo.com',
            'www.techcrunch.com',
            'www.this_one_wont_work.com'
           ]
        Pinger(hosts)
    
    0 讨论(0)
  • 2020-11-22 09:48

    read a file name, the file contain the one url per line, like this:

    http://www.poolsaboveground.com/apache/hadoop/core/
    http://mirrors.sonic.net/apache/hadoop/core/
    

    use command:

    python url.py urls.txt
    

    get the result:

    Round Trip Time: 253 ms - mirrors.sonic.net
    Round Trip Time: 245 ms - www.globalish.com
    Round Trip Time: 327 ms - www.poolsaboveground.com
    

    source code(url.py):

    import re
    import sys
    import urlparse
    from subprocess import Popen, PIPE
    from threading import Thread
    
    
    class Pinger(object):
        def __init__(self, hosts):
            for host in hosts:
                hostname = urlparse.urlparse(host).hostname
                if hostname:
                    pa = PingAgent(hostname)
                    pa.start()
                else:
                    continue
    
    class PingAgent(Thread):
        def __init__(self, host):
            Thread.__init__(self)        
            self.host = host
    
        def run(self):
            p = Popen('ping -n 1 ' + self.host, stdout=PIPE)
            m = re.search('Average = (.*)ms', p.stdout.read())
            if m: print 'Round Trip Time: %s ms -' % m.group(1), self.host
            else: print 'Error: Invalid Response -', self.host
    
    
    if __name__ == '__main__':
        with open(sys.argv[1]) as f:
            content = f.readlines() 
        Pinger(content)
    
    0 讨论(0)
  • 2020-11-22 09:52

    Use this it's tested on python 2.7 and works fine it returns ping time in milliseconds if success and return False on fail.

    import platform,subproccess,re
    def Ping(hostname,timeout):
        if platform.system() == "Windows":
            command="ping "+hostname+" -n 1 -w "+str(timeout*1000)
        else:
            command="ping -i "+str(timeout)+" -c 1 " + hostname
        proccess = subprocess.Popen(command, stdout=subprocess.PIPE)
        matches=re.match('.*time=([0-9]+)ms.*', proccess.stdout.read(),re.DOTALL)
        if matches:
            return matches.group(1)
        else: 
            return False
    
    0 讨论(0)
  • 2020-11-22 09:52

    I develop a library that I think could help you. It is called icmplib (unrelated to any other code of the same name that can be found on the Internet) and is a pure implementation of the ICMP protocol in Python.

    It is completely object oriented and has simple functions such as the classic ping, multiping and traceroute, as well as low level classes and sockets for those who want to develop applications based on the ICMP protocol.

    Here are some other highlights:

    • Can be run without root privileges.
    • You can customize many parameters such as the payload of ICMP packets and the traffic class (QoS).
    • Cross-platform: tested on Linux, macOS and Windows.
    • Fast and requires few CPU / RAM resources unlike calls made with subprocess.
    • Lightweight and does not rely on any additional dependencies.

    To install it (Python 3.6+ required):

    pip3 install icmplib
    

    Here is a simple example of the ping function:

    host = ping('1.1.1.1', count=4, interval=1, timeout=2, privileged=True)
    
    if host.is_alive:
        print(f'{host.address} is alive! avg_rtt={host.avg_rtt} ms')
    else:
        print(f'{host.address} is dead')
    

    Set the "privileged" parameter to False if you want to use the library without root privileges.

    You can find the complete documentation on the project page: https://github.com/ValentinBELYN/icmplib

    Hope you will find this library useful. Please do not hesitate to send me your comments on GitHub, suggestions for improving it, or any problems you encounter while using it.

    0 讨论(0)
提交回复
热议问题