Auto-Deploying Configuration

The other day I finally got around to writing a script to automatically deploy config to a bunch of devices. Finally! I have been planning on doing this for a number of years (I think eight years since I originally said I would). It just turned out that every time I kinda/sorta/maybe needed it over the last decade or so, it turned out that I could do it manually for just a little bit less effort.

Those days have a last come to an end.

The script I have written is pretty basic but it gets the job done. It is written to be used using an expect command on any linux device. This script Telnets (could be modified to SSH easily) to some devices (in this case 192.168.1.1 and 192.168.1.2), logs in using the provided username and password (set in the cryptically named username and password variables). Then it applies all the commands listed in allCommands to all the devices and applies the commands for that device from the deviceCommands list. The variable deviceCommands is a “list of lists”. Each line corresponds to an IP address in the hosts variable. If you need the same command on a couple of devices then you need to copy that command a couple of times.

This script is written around using a Cisco device. Some of the expect lines would need to be modified if it was going to be used on some other devices which output different prompts. For example, after each line it expects something ending in # – the standard output for a Cisco device in enable mode. This would need to change as required.

So, without further delay, here it is, in all its simple glory. If anyone has anything better or a modification on this, feel free to post.

#!/usr/bin/expect -f

#List of host ip addresses
set hosts [list "192.168.1.1" "192.168.1.2"]

set username "admin"
set password "password"

#Commands to be applied to all devices
set allCommands [list "!" "!!" "!!!"]

#Commands to be applied only to individual devices, each sub-list corresponds to one IP address above in the hosts list.
set deviceCommands {{"int f0/20" "!"} {"int f0/21" "!"}}

set counter 0

foreach hostaddr $hosts {

 #Could ssh here if required
 spawn telnet $hostaddr

 #Login here:
 expect "Username:"
 send $username\r
 expect "Password:"
 send $password\r
 expect "*#"

 #Enter config mode:
 send "conf t\r"
 expect "*#"

 #Add global commands to all devices
 foreach command $allCommands {
  send $command\r
  expect "*#"
 }

 #Add the per-device commands
 set subsetCommand [lindex $deviceCommands $counter]
 foreach command $subsetCommand {
  send $command\r
  expect "*#"
 }
 
 #Exit config mode
 send "end\r"
 expect "*#"

 #Write config
 send "wri\r"
 expect "*#"

 #Exit telnet/ssh
 send "exit\r"
 incr counter +1
}

 

This entry was posted in Config by Tom. Bookmark the permalink.

Leave a Reply

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