I am trying to create an expect script which will send a different password string based on the “expect”
-
Condition A: If a cisco device has not been setup with a username then the first prompt will simply be “Password:” – then it should use passwordA (no username)
-
Condition B: If it has been setup with a username then the prompt will be “Username:” followed by “Password:” – then it should use Username and PasswordB
#!/bin/bash
# Declare host variable as the input variable
host=$1
# Start the expect script
(expect -c "
set timeout 20
# Start the session with the input variable and the rest of the hostname
spawn telnet $host
set timeout 3
if {expect \"Password:\"} {
send \"PasswordA\"}
elseif { expect \"Username:\"}
send \"UsersName\r\"}
expect \"Password:\"
log_user 0
send \"PasswordB\r\"
log_user 1
expect \"*>\"
# send \"show version\r\"
# set results $expect_out(buffer)
#expect \"Password:\"
#send \"SomeEnablePassword\r\"
# Allow us to interact with the switch ourselves
# stop the expect script once the telnet session is closed
send \"quit\r\"
expect eof
")
You’re doing it wrong. 🙂
The
expectstatement doesn’t look to see what comes first, it waits until it sees what you ask for (and times out if it doesn’t arrive in time), and then runs a command you pass to it. I think you can use it something like the way you’re trying to, but it’s not good.expectcan take a list of alternatives to look for, like a Cswitchstatement, or a shellcasestatement, and that’s what you need here.I’ve not tested this, but what you want should look something like this:
In words, expect will look for either “Username:” or “Password:” (
-exmeans exact match, no regexp), whichever comes first, and run the command associated with it.In response to the comments, I would try a second password like this (assuming that a successful login gives a ‘#’ prompt):
You could do it without looking for the
#prompt, but you’d have to rely on the secondPassword:expect timing-out, which isn’t ideal.