Tuesday, March 19, 2013

Using Bash scripting to automate Network Administrative Tasks

Automating repetitive tasks is an essential skill for any Systems Administrator or Network Administrator.  The following script is a trick I have used for years to push configuration commands to network switches or other network devices that have a telnet interface.  (Yes, there is an assumed risk of the plain text telnet password.)  If you have multiple devices that need the same configuration, you can push these changes to them via a loop in a bash script.  This script accepts input from a text file and then echoes a series of commands to the network device.  The following is an example in which we need to push an SNMP community and access control list to a series of Cisco switches.

#!/bin/sh
cat switches.txt | while read SWITCH
do(
        sleep 1
        echo myusername   
        sleep 1
        echo P@55w0rd
        sleep 1
        echo en
        sleep 1
        echo P@ssword
        sleep 1
        echo config t
        sleep 1
        echo access-list 41 permit 10.10.10.1
        sleep 1
        echo access-list 41 permit 192.168.0.1
        sleep 1
        echo snmp-server community myCommunity RW 41
        sleep 1
        echo wr
) | telnet $SWITCH
done

First the script reads the switch IP address from a text file (the password could be read in too).  The script then uses the "echo" command to send the configuration to the telnet command.  You will see the first several commands initiate the log in and then invoke enable mode (en).  The sleep statements in between each command give the switch time to process the previous command before receiving the subsequent one.  Finally, the script then enters into the configuration terminal (config t) creates an access list with entries, and then assigns it to a read/write SNMP community.  The switches.txt file would have one IP address per line for each switch that would need this configuration.  If you wanted to read in other information like a password, just tab separate the data and another variable after SWITCH in the cat switches.txt... line.  I have also used this method to periodically reboot Blackboard Vending units as well as push configurations to them and to tftp switch configurations back to a storage server.

The above script should work on any Linux machine including a Raspberry Pi, which would make a very inexpensive server to run this script and other similar scripts.





No comments:

Post a Comment