Making decisions on expect return

喜你入骨 提交于 2020-02-06 11:13:59

问题


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
")

回答1:


You're doing it wrong. :)

The expect statement 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.

expect can take a list of alternatives to look for, like a C switch statement, or a shell case statement, and that's what you need here.

I've not tested this, but what you want should look something like this:

expect {
  -ex "Username:" {
    send "UsersName\r"
    expect -ex "Password:" {send "PasswordB\r"}
  }
  -ex "Password:" {send "PasswordA\r"}
}

In words, expect will look for either "Username:" or "Password:" (-ex means 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):

expect {
  -ex "Username:" {
    send "UsersName\r"
    expect -ex "Password:" {send "PasswordB\r"}
  }
  -ex "Password:" {
    send "PasswordA1\r"
    expect {
      -ex "Password:" {send "PasswordA2\r"}
      -ex "#" {}
    }
  }
}

You could do it without looking for the # prompt, but you'd have to rely on the second Password: expect timing-out, which isn't ideal.



来源:https://stackoverflow.com/questions/13084870/making-decisions-on-expect-return

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!