You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Expect自动化Docker容器部署中的非连续交互输入?

Using Expect to Automate Your Docker Deployment Interactive Prompts

Absolutely! Expect was built specifically to handle this kind of non-sequential interactive command-line flow—perfect for your scenario where prompts pop up at different stages. Let me walk you through a tailored solution:

Step 1: First, Make Sure Expect is Installed

Most systems have Expect pre-installed, but if not:

  • On Debian/Ubuntu: sudo apt install expect
  • On macOS: brew install expect

Step 2: Custom Expect Script Example

Here’s a script built to match your exact workflow—just tweak the values and prompt strings to match your deployment tool’s output:

#!/usr/bin/expect

# Set a timeout (adjust this if your OpenVPN script takes longer than 60s to run)
set timeout 60

# Define your values upfront (easy to update later)
set vpn_pass "your_secure_vpn_password"
set cert_fqdn "your.target.domain.com"

# Launch your actual Docker deployment command here
spawn docker run [your-container-flags-and-options] your-image-name

# Handle the first two consecutive password prompts
expect "Enter password:"
send "$vpn_pass\r"

expect "Confirm password:"
send "$vpn_pass\r"

# Wait for OpenVPN to finish executing—replace this string with the exact line your script outputs when done
expect "OpenVPN setup completed successfully"

# Now send the FQDN when the certificate prompt appears
expect "Enter FQDN for certificate generation:"
send "$cert_fqdn\r"

# Wait for the entire deployment to finish (wait for the process to exit)
expect eof

Critical Customization Tips

  • Match prompts exactly: Expect relies on matching the exact text of the prompts. If your tool uses slightly different wording (like "Password:" instead of "Enter password:"), update the strings in the expect blocks. Use expect -d ./your-script.exp to debug if matching fails.
  • Adjust timeout: If your OpenVPN setup takes longer than 60 seconds, increase the set timeout value (use -1 for no timeout if needed).
  • Handle edge cases: Add fallback expect blocks to catch errors, like invalid password warnings:
    expect {
      "Error: Password mismatch" {
        puts "Password confirmation failed! Exiting."
        exit 1
      }
      "OpenVPN setup completed successfully" {
        # Proceed to FQDN prompt
      }
    }
    
  • Make it executable: Run chmod +x deploy-automator.exp, then launch it with ./deploy-automator.exp.

Why Not Use yes or Piped Input?

Tools like yes or piping input with printf work for sequential prompts, but they can’t handle delays (like waiting for OpenVPN to finish running) between inputs. Expect’s ability to wait for specific output makes it the only reliable tool here.

内容的提问来源于stack exchange,提问作者William

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 04:20:57