Python Pexpect and Cisco IOS

Hello User!,

Lets say you have a couple of Cisco Switches in your environment on which you need to automate some tasks like switching the interfaces such that the device in path gets redirected or if you would like to take backup after running your tests. Manually switching or taking backup of the entire environment filled with catalyst switches and Cisco Routers isn’t fun either. So here is a little experiment using python and pexpect that runs any show command and can also do a backup of a cisco device. There is much improvement to be done and you can tweak this better to run some CLI changes that you are planning. But meh, this is just a starting script and an experiment.

#!/usr/bin/env python
#This Script expects you are providing a level 15 user priveledge
#Uses FTP & Telnet and is insecure
#Will work if run through a linux terminal, not windows
#needs ftp server setup and username password added in the cisco device
#and is only a sample reference to get started.
import pexpect
import sys
import time
import datetime

class CiscoSwitch():
    def __init__(self, host, username, password):
        self.username = username = host
        self.password = password

    def Login(self):
        self.child = pexpect.spawn('telnet '
        self.child.sendline('terminal length 0')
        return (self.child, self.child.before)

    def RunShowCmd(self,cmd):
        return (self.child, self.child.before)
    def FtpBackupCmd(self,ftpip):
        self.child.sendline('copy running-config ftp:')
        DATE ='%Y_%m_%d_%H_%M_%S')
        return (self.child, self.child.before)

if __name__ == '__main__':
    	print 'This program is being run by itself'
        Switch = CiscoSwitch('','admin','freebsd')
        (obj,stdout) = Switch.Login()
        print stdout
        (obj,stdout) = Switch.RunShowCmd('show ip int brief')
        print stdout
        (obj,stdout) = Switch.FtpBackupCmd('')
        print stdout

Published by Ramnath Shenoy

I work a penetration tester and this blog is just some of my personal notes!

Leave a comment

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: