首页 > 解决方案 > 有没有办法在 TCL 中使用 IF CONDITION 期望语句?

问题描述

有没有办法我可以 IF CONDITION 一个期望命令。例如在下面的代码中,我尝试 ssh 到特定的 IP 地址,有时它会问我“你确定要继续连接(是/否)吗?” 有时它不会。我如何做到这一点,如果它显示我发送“是/r”,如果它没有,我继续我的代码?

set name="123.456.78.910"
expect "$ "     ;       send -- "ssh root@$name\r"
expect {
  "Password:" { send "password" }
  timeout   { sleep 1 }

}

expect "Are you sure you want to continue connecting (yes/no)?" ; send -- "yes\r”

标签: tclexpect

解决方案


这是exp_continue命令的目的:

spawn ssh user@host

set prompt {\$ $}    ;# or whatever regex your prompt matches

expect {
    timeout {error "timed out connecting to host"}
    "continue connecting" {send "yes\r"; exp_continue}
    "Password:" {send "$password\r"; exp_continue}
    -re $prompt
}

send "do stuff\r"
# ...

如果期望超时,脚本会出错。
如果您收到“继续连接”提示,请发送“是”并继续期待。
如果您收到“密码”提示,请发送您的密码并继续期待。
你得到你的 shell 提示时,expect命令完成并且你继续你的程序。


推荐阅读