Ssh – Script SSH to router and “enable” and run commands

bashciscorouterssh

I have a script that will ssh to a list of routers and run commands from commands.txt. I want to enable after I connect to the router through ssh before I execute the rest of my commands in commands.txt I have two questions. First, how do I pass the enable command? It doesnt seem to be doing anything when I put it as my first line in commands.txt.Second, Once I figure out the enable prompt part, how would I pass my credentials for the script to be fully automatic?

Script

enter image description here

Commands.txt

enter image description here

When I run this current script I enter my password when it prompts me for connection to the router. Then it just displays % Type "show ?" for a list of subcommands and then goes on and connects to the next router and asks for my credentials.

Best Answer

Consider looking at RANCID. It's primarily intended as a configuration backup tool for Cisco and other networking devices, but one of its components, clogin, is essentially an Expect script that does exactly what you're asking. Using the command and router file listings in your example, you could execute the commands on all routers like this:

clogin -u user -p pass -e enablepass -x commands.txt $(cat routers.txt)

It can read a configuration file in which you can store login names and passwords, so you can avoid passing them on the command line. It has multiple login options, so it can deal with cases where you aren't using aaa new-model and just have passwords on the VTYs, and cases with older gear that asks for the username in response to the enable command.

The only real downside is that it's not especially quiet. For instance, if you want the output of show version, you'll get that, but you'll also get all the login banners, login/passwords prompts, and command prompts in your output.