如何使用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
expectblocks. Useexpect -d ./your-script.expto debug if matching fails. - Adjust timeout: If your OpenVPN setup takes longer than 60 seconds, increase the
set timeoutvalue (use-1for no timeout if needed). - Handle edge cases: Add fallback
expectblocks 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
相关产品推荐
相关产品推荐

