Python Scripting for HP Procurve Switches

I’ve working for the last several months on setting up a disaster recovery site, part of which required scripting network changes to streamline the process of making the site hot when necessary.  I wanted to connect from the scripting server to my networking devices via SSH for security purposes and I didn’t want to necessarily rely on using SSH keys.  For this task I chose to use Python 2.7 and Pexpect 3.3.  Initially I was hoping to use Pxssh which is included in Pexpect, but I was unsuccessful in getting being able to get Pxssh to work around issues with initial log-in messages and setting the command prompt.

I will create additional posts to supplement  this basic tutorial in the near future.

First, let’s make sure that the prerequisites are satisfied.

  1. You have a Linux machine of some variety available.
  2. You have Python 2.x installed.
  3. You have installed Pip, Pexpect and Netaddr
    wget https://bootstrap.pypa.io/get-pip.py
    python get-pip.py
    pip install pexpect
    pip install netaddr

Let’s build a simple test to verify connectivity

# Import modules needed for script
import pexpect
import getpass

# Setup Username, Hostname and Password
hostname = raw_input('hostname: ')
username = raw_input('username: ')
password = getpass.getpass('password: ')

# Spawn SSH session to the host
s = pexpect.spawn('ssh %s@%s' % (username, hostname))

# Expect the switch to prompt for a password
s.expect('.*assword: ')

# Send the password
s.sendline(password)

# Expect the MOTD to end with 
s.expect('Press any key to continue')

# Send the return key
s.send('\r')

# Interact with the shell
s.interact()

Let’s drop:

# Interact with the shell
s.interact()

And add:

# Show the running configuration or substitute other commands
s.expect('.*\w+#') #Find the prompt
s.sendline('show running-config')

# Once the terminal window fills, we need to press the spacebar to continue printing the config
nextpage = s.expect(['--.*\w+l-C', '.*\w+#']) 
while nextpage == 0:
  # print everything before came before the continue message
  print s.before
  s.send(' ')
  nextpage = s.expect(['--.*\w+l-C', '.*\w+#'])
# Now we are out of the while loop so we need to print everything after that.
print s.after

In my next post, we’ll look at how to take the data gathered above and perform useful tasks with it.

Leave a comment

Your email address will not be published. Required fields are marked *

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