Networking Scripting

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
    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 %[email protected]%s' % (username, hostname))

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

# Send the password

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

# Send the return key

# Interact with the shell

Let’s drop:

# Interact with the shell

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 Reply

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