bash 脚本中的 expect 语句用于预期输出的错误验证

expect statement in bash script for error validation of expected output

我的 bash 脚本中有以下 expect 语句:

/usr/bin/expect << EOF
spawn -noecho lucli users add -username user -role admin -email 
user@user.com
expect "password:" { send "password\n" }
expect "password:" { send "password\n" }
expect eof
EOF

我希望 expect 脚本验证 CLI 命令在传递密码并创建用户后是否返回了正确的输出。

返回的我要验证的消息是 "added to the system successfully"

我不知道如何使用 expect 在 bash 脚本中做到这一点。

有人可以帮忙吗?

您可以尝试这样的操作:

# note the quoted here-doc word
status=$(/usr/bin/expect << 'EOF'
    spawn -noecho lucli users add -username user -role admin -email 
    user@user.com
    expect "password:" { send "password\r" }
    expect "password:" { send "password\r" }
    expect eof
    set status [string match "*added to the system successfully*" $expect_out(buffer)]
    # $status will be the C-like boolean 0 or 1
    exit $status
EOF
)
if [[ $status -eq 1 ]]; then
    echo "user added OK"
else
    echo "user not added"
fi

参考:https://tcl.tk/man/tcl8.6/TclCmd/string.htm