Multithreaded Telnet sessions

Eddie Corns eddie at holyrood.ed.ac.uk
Mon Jun 14 07:12:11 EDT 2004


linux at myprincesspearls.com (Richard Bird  CCNP, CCDP, MCSE, etc.) writes:

>I need some help adding multithreading to an existing python script.
>The script was developed to telnet and make changes on a list of cisco
>routers.
>I figure that by adding multithreading, I'd be able to telnet to
>several routers concurrently and speed up the process of making
>changes.

>Is this feasible using python with its standard telnet lib?

Yup.  Here's the skeleton of code that I use to pull the ARP table from a
bunch of Cisco routers.

---------------------------------------------------------------------------
from threading import Thread, currentThread

# example of how to show which router an error occured on
def warn (msg):
    stderr.write ('%s::%s\n' % (currentThread.getName(),msg))

# code to do things to the router
def do_router_things (rtr):
    # open connection ...
    # do the stuff
    # close connection
    # all done

# start a thread for each router
threads = []
for rtr in ...:
    th = Thread(name=rtr, target=do_router_things, args=(rtr,))
    th.start()
    threads.append (th)

# wait for all threads to finish
for th in threads:
    th.join()
---------------------------------------------------------------------------

Though if the processes were as independent as that I would just use a
separate process for each one (on Unix anyway).  If you're collecting data
that needs to be processed then you would probably use a Queue.Queue, pass the
data INTO the Queue from do_router_things and have one more thread that pulls
items FROM the Queue.

HTH, mail me if you'd like more help.

Eddie



More information about the Python-list mailing list