期望:exit/finish/close 对返回的输出进行交互

Expect: exit/finish/close interact on returned output

我需要使用 expect 来导航程序菜单,然后允许用户输入。用户完成输入后,如果该程序返回特定字符串,我需要告诉 expect 取消用户控制。

expect -c '
[login etc, navigate to the desired option]
expect "[string]"; interact
[user input] -> until here everything works

expect "[specific string returned by the PROGRAM, NOT user input]"
[take away control from the user / exit interact if the above specific string is returned] -> this doesn't work

expect "string"; send "[exit command]\r"' -> what should happen after

此外,我需要捕获所有可能的信号,因为如果使用其中之一,用户最终可能会进入具有根访问权限的 shell cli。

几个小时以来,我一直在努力寻找答案,但我试图在 expect 中生成有效语法的尝试以失败告终,因为文档在这方面对我没有任何帮助。

这是一个例子。 Expect 将控制此 shell 脚本:

#!/bin/sh
PS3="your choice? "
select answer in foo bar baz quit; do
    case $answer in
        quit) echo "bye bye"; break;;
        *) echo "you chose $answer";;
    esac
done
echo "out of select loop: hit enter..."
read x
echo "exiting ..."

期望的程序是:

#!/usr/bin/env expect

spawn sh test.sh

set keyword "out of select loop"

# signal handlers: ignore these (can't trap SIGKILL)
trap SIG_IGN {HUP INT TERM QUIT}

# interact until a certain pattern is seen
# in the output (-o) of the process
interact {
    [=11=]3 {
        # prevent the user sending SIGINT to the spawned process
        puts "don't press Ctrl-C again"
    }
    -o $keyword {
        send_user "you quit\n"
        send_user $keyword
        return                  # "return" exits the interact command
    }
}

# do other stuff here, for example, hit enter to allow the 
# shell script to terminate
expect -re {\.\.\.\s*$}
send_user "... hitting enter ...\n"
send -- \r
expect eof

expect 手册页很粗糙。 Exploring Expect 这本书会让你更开心。