在 Bash 脚本中优化 Expect

问题描述 投票:0回答:1

我在 Stack Overflow 上阅读了很多主题,但还没有成功地用 Expect 优化我的 Bash 脚本。

首先是一些背景。我需要在 macOS 上运行交互式命令。这是将引导令牌托管到 MDM 服务器的命令。这是必需的,因为这不会在我们的工作流程中自动完成。

我为此创建了以下脚本。很基本;它获取 Base64 中的用户名和密码,对其进行解码,然后运行命令。

# Get Jamf Pro Parameters
base64username=$4
base64password=$5

# Decode Base64 Parameters
username="$(echo "$base64username" | base64 -d)"
password="$(echo "$base64password" | base64 -d)"

# Escrow Bootstrap Token
expect -c "spawn profiles install -type bootstraptoken
expect \"Enter the admin user name:\"
send \"$username\r\"
expect \"Enter the password for user '$username':\"
send \"$password\r\"
expect \"profiles: Bootstrap Token escrowed\""

总的来说效果很好,但事实证明不可靠。经过大量试验和错误后,我很确定这是因为 Bash 中 Expect 的默认超时为 10 秒。有时运行命令需要更多时间。

所以我想将超时设置为 60 秒,但不知道如何正确设置。如果可能的话,如果命令没有返回成功的托管,我想使用退出代码。

有人愿意帮助我吗?非常感谢!

bash macos expect
1个回答
1
投票

您将 expect

timeout
变量设置为特殊值
-1
。默认超时为 10 秒。 -1 表示“无限”。

此外,您可以通过环境传递 shell 值以期望,这使得引用更容易:

export username password

expect -c '
    spawn profiles install -type bootstraptoken
    expect "Enter the admin user name:"
    send "$env(username)\r"
    expect "Enter the password for user "
    send "$env(password)\r"

    set timeout -1
    expect "profiles: Bootstrap Token escrowed"
'

如果命令返回“profiles: Bootstrap Token escrowed”,我想退出 0,如果没有其他情况,我想退出 1。

其中一个非常酷的功能是您可以同时预期几件事并在遇到该模式时执行操作。

eof
在派生进程退出时发生。

expect {
    "profiles: Bootstrap Token escrowed" {exit 0}
    eof {exit 1}
}
© www.soinside.com 2019 - 2024. All rights reserved.