Ping a site in Python?

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

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

15条回答
  •  眼角桃花
    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)
    

提交回复
热议问题