Ping a site in Python?

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

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

15条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 09:57

    You may find Noah Gift's presentation Creating Agile Commandline Tools With Python. In it he combines subprocess, Queue and threading to develop solution that is capable of pinging hosts concurrently and speeding up the process. Below is a basic version before he adds command line parsing and some other features. The code to this version and others can be found here

    #!/usr/bin/env python2.5
    from threading import Thread
    import subprocess
    from Queue import Queue
    
    num_threads = 4
    queue = Queue()
    ips = ["10.0.1.1", "10.0.1.3", "10.0.1.11", "10.0.1.51"]
    #wraps system ping command
    def pinger(i, q):
        """Pings subnet"""
        while True:
            ip = q.get()
            print "Thread %s: Pinging %s" % (i, ip)
            ret = subprocess.call("ping -c 1 %s" % ip,
                shell=True,
                stdout=open('/dev/null', 'w'),
                stderr=subprocess.STDOUT)
            if ret == 0:
                print "%s: is alive" % ip
            else:
                print "%s: did not respond" % ip
            q.task_done()
    #Spawn thread pool
    for i in range(num_threads):
    
        worker = Thread(target=pinger, args=(i, queue))
        worker.setDaemon(True)
        worker.start()
    #Place work in queue
    for ip in ips:
        queue.put(ip)
    #Wait until worker threads are done to exit    
    queue.join()
    

    He is also author of: Python for Unix and Linux System Administration

    http://ecx.images-amazon.com/images/I/515qmR%2B4sjL._SL500_AA240_.jpg

提交回复
热议问题