Ping a site in Python?

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

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

15条回答
  •  天命终不由人
    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)
    

提交回复
热议问题