ping multiple Ips with python

Branimir Petrovic BranimirPetrovic at yahoo.com
Tue Jan 7 05:10:06 CET 2003


dhostetler at sopris.net (.d.hos) wrote in message news:<8db020b9.0301061545.48785623 at posting.google.com>...

> 
> I looked into other multithreaded examples on the web and came up with
> the following:
> 
> =============================
> import threading, os
> 
> def log(s):
>     print s
> 
> class Pinger(threading.Thread):
>     def __init__(self, address, *args, **kwargs):
>         self.address = address       
>         threading.Thread.__init__(self, *args, **kwargs)        
> 
>     def run(self):
>         pingCard = "ping -n 10 " + self.address
>         child = os.popen(pingCard).readlines()
>         log(child)      
> 
> 
> if __name__ == '__main__':
>     
>     PingList = ["127.0.0.1", "66.218.71.83", "64.66.148.171"]
>     threadList = []
>     
>     # Create threads
>     for i in PingList :        
>         threadList.append(Pinger(i))
> 
>     # Start all threads
>     for thread in threadList:
>         thread.start()
> ============================================
> 
> when run through idle, the python shell hangs after all the ips
> respond. Do I have to stop each thread individually after it executes
> the ping command? other than that it seems to work....
> 

"""Being Python newbie myself, also interested in multithreading,
I reworked slightly your code, adding (what I beleive) thread
safe output. Threads will die having depleated all assigned 
tasks after pushing results into passed Queue instance (or when 
run method ends). Your issue with idle is probably idle related, 
your code (and my mod too) runs just fine from command line. 

Quite amazing what Python can do in only few lines of code...

Branimir
"""

import threading, os, Queue, time

def showResponse(args):
    """Pretty prints passed tuple to stdout"""

    stdoutLi, ip, threadNo = args
    print 'Host   \t%s \nThread \t%s\n' % (ip, threadNo)

    for line in stdoutLi:
        line = line.strip()
        if not line: continue
        print '\t' + line
    print '='*72

class Pinger(threading.Thread):
    def __init__(self, address, queue, threadNo=None):
        self.__address = address
        self.__queue = queue
        self.__threadNo = threadNo
        threading.Thread.__init__(self)

    def run(self):
        pingCmd = "ping -n 1 -w 3000 " + self.__address
        childStdout = os.popen(pingCmd)
        result = (childStdout.readlines(), self.__address, self.__threadNo)
        childStdout.close()
        self.__queue.put(result)


if __name__ == '__main__':

    # watch dog timeout value (allow __main__ to run up to N seconds)
    wdt = 10.0

    # make list of hosts to ping
    hostLi = ["127.0.0.1", "66.218.71.83", "64.66.148.171"]
    # ping results go to the Queue's instance
    q = Queue.Queue()

    i = 0
    while i < len(hostLi):
        """Create and start all necessary threads, passing results
        out via thread safe Queue instance.

        It probably is a bad idea to start too many concurrent threads?
        """

        Pinger(hostLi[i], q, i+1).start()
        i +=1

    startT = time.time()

    while i > 0 and ((time.time() - startT) < wdt):
        """Loop ends when: 
                All responses to dispatched pings arrive,
                    OR
                Max allowed wait time is exceeded"""

        showResponse(q.get())
        i -= 1




More information about the Python-list mailing list