1

I'm writing a script with expect to configure cisco routers automatically via ssh. A part of this script is to copy an image into flash if it doesn't exist:

For this expect sends a copy and waits for Destination filename then sends a return.

cisco#copy tftp://10.xx.xx.3/name_of_image.bin flash:
Destination filename [name_of_image.bin]?

Now there're two options:

  1. The File doesn't exist and gets copied into flash:
  2. The File exists and the script skips this part.

If the file already exists it looks like this:

%Warning:There is a file already existing with this name
Do you want to over write? [confirm]

Now to my problem: The scripts waits for Do you want to over write? [confirm] and then should exit since the image is already in flash. But currently it seems like expect can't recognize that line and gets stuck at the confirmation. It've tried several patterns like [confirm], *[confirm]*, Do, *write* and some more.

My code for that job looks like this at the moment:

        expect "*#"
        send "copy tftp://10.$ip_local.3/name_of_image.bin flash:\r"
        expect "Destination filename"
        send "\r"

        expect {
          "Do you want to over write? [confirm]"{
           interact
           abort
        }
        expect "*#"
        send "exit\r"

What am I doing wrong?

SummerRain
  • 13
  • 2

1 Answers1

0

A couple of things wrong:

  • in a double-quoted string [confirm] will attempt to call the expect command "confirm" -- square brackets in expect are like backticks in the shell
  • expect needs to have arguments separated by whitespace. Therefore it's critical to put a space before the opening curly brace
  • your script does not expect the overwrite prompt conditionally. You need to use the multi-pattern form of the expect command, where the first one matched wins.

Try this:

expect {
    -exact {Do you want to over write? [confirm]} {
        send "\r"
        exp_continue
    }
    "*#"
}
send "exit\r"
expect eof

Notes

  • I'm using "exact" matching since you have glob wildcards ? and [...] that would interfere.
  • I'm using expect's no-interpolation quotes (curly braces) to prevent [confirm] from attempting command substitution
  • I expect either the overwrite prompt or the command prompt
  • I use exp_continue to remain within this expect command if the overwrite prompt appears. That means that I can still look for the command prompt.
  • the above 2 bullets are how to implement conditional matching.
  • I assume you just want to hit enter at the overwrite prompt.
  • after you exit, wait for eof to allow the ssh session to end normally
glenn jackman
  • 4,630
  • 1
  • 17
  • 20