在期望脚本中等待提示

Ulr*_*rik 4 prompt telnet expect

我需要一个expect脚本来等待已发出的命令完成,然后从中注销telnet.这是脚本:

spawn telnet host
send "username\r"
send "password\r"
sleep 3
send "custom_command\r"
while {???}
{
    sleep 1
}
send "logout\r"
expect eof
Run Code Online (Sandbox Code Playgroud)

我不知道该怎么说的部分是???.我基本上只需要等待prompt显示,一旦显示,脚本应该结束.我猜它应该是这样的[gets line != "prompt>" ].

gle*_*man 6

在发送内容之前,你应该真正期待一些事情,以确保正确的时机.就像是:

exp_internal 1      ;# expect internal debugging. remove when not needed
spawn telnet host
expect "login: "
send "username\r"
expect "Password: "
send "password\r"
set prompt {\$ $}   ;# this is a regular expression to match the *end* of
                     # your shell prompt. Adjust as required.
expect -re $prompt
send "custom_command\r"
expect -re $prompt
send "logout\r"
expect eof
Run Code Online (Sandbox Code Playgroud)


Ulr*_*rik 5

我尝试了Expect命令,但是在经过一些研究,反复试验后,我发现以下内容无效:

  1. 使用expect "prompt>\r"代替expect "prompt>"
  2. 花括号必须与Expect命令位于同一行,像这样 expect "prompt>\r" {
  3. 使用set timeout -1等待无限提示,而不是10秒

因此,答案是:

spawn telnet host
send "username\r"
send "password\r"
sleep 3
set timeout -1
send "custom_command\r"
expect "prompt>\r" {
    send "logout\r"
    expect eof
}
Run Code Online (Sandbox Code Playgroud)


ssn*_*ody 2

这里的expect命令似乎是合适的expect接下来expect "prompt\n"是发送注销信息。

请注意,如果这是普通的 telnet 系统,您通常应该等待提示输入用户名和密码,然后再发送。了解如何使用expectexpect脚本自动执行telnet会话以自动执行telnet登录