Python Telnet Code

by Brian on 7/23/2007

I found this useful bit of Python code for implementing scriptable telnet sessions. The above linked version of code seems to have been written in 2002 and appears to have a few problems with Python v2.5.x. I’ve made a few modifications and you can download my version here. Tim Keating is the original author of the script.

I use this script to do some administration work on Cisco routers. I’m sure there are a couple of nifty things you could do with it, such as make a script to download and backup all your router configs.

You script your telnet sessions like this:
script =
“”"ru Username:
w user
ru Password:
w yourpass
ru ROUTER#
w terminal length 0
ru ROUTER#
w show config
ru ROUTER#
cl
“”"

Execute the script like this:
con = telnetscript.telnetscript(‘yourserver.com’)
self.config = con.RunScript(self.script.split(‘\n’))
self.config = self.config.split(‘\n’)

Results will be stored in the above example as an array of strings in self.config.

Related posts:

  1. Default Timeouts in Python urllib2
  2. Cisco Thinks You Should Run Your Web App on The Router
  3. Netbeans Ruby Code Completion
  • Mattonm

    Thanks Brian!  I just took a quick look at your post and think it might contain one of the pieces I need.  I want to change the port forwarding address on my router to a backup internal web server address if the primary web server loses connectivity.  I hoping I can script something to monitor the port on the primary and have it telnet in to the router and switch the port 80 forwarding ip to the backup.

  • http://www.brianjones.ca joshaidan

    You’re welcome Mattonm. This little snipplet should accomplish what you’re trying to do. I’m using it to do something similar, make changes on a router automatically.

Previous post:

Next post: