期望:退出/完成/关闭在返回的输出上进行交互

时间:2015-03-25 18:18:06

标签: tcl 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

此外,我需要捕获所有可能的信号,因为如果使用其中一个信号,则用户可以以root访问权限终止于shell cli。

我一直试图在这个问题上找到答案好几个小时,但我在expect内制作有效语法的尝试最终令人沮丧,因为文档在这方面根本没有帮助我。 / p>

1 个答案:

答案 0 :(得分:1)

这是一个适合你的例子。 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 {
    \003 {
        # 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

期望的男人页面很粗糙。你会对“探索期待”一书感到高兴。