如何用Expect实现脚本自动化:已知问题自动回复,未知问题人工交互
Hey there! I see you want to automate responses to known prompts in your bash script using Expect, while letting users handle unexpected questions manually. That's a common use case, and here's a straightforward solution:
Automate Known Prompts with Expect, Fallback to Manual Input for Unknown Ones
Step 1: Create the Expect Script
Let's build an Expect script (name it auto_reply.exp) that monitors your script.sh output, auto-replies to predefined questions, and hands off control to the user for unrecognized prompts.
#!/usr/bin/expect -f # Launch your bash script spawn ./script.sh # Disable timeout so Expect waits indefinitely for prompts set timeout -1 # Loop to handle all prompts until the script exits while {1} { expect { # Auto-reply to your known questions "Would you like tea ?" { send "Yes, please!\r" exp_continue # Keep listening for next prompts } "Would you like car ?" { send "No, thanks!\r" exp_continue } # Catch unknown prompts (matches any line ending with a question mark) -re {.*\?} { # Print the unexpected prompt for the user puts "\nUnexpected prompt: [expect_out(buffer)]" puts "Please enter your response manually:" # Switch to manual input mode (disable terminal echo temporarily) stty raw -echo gets stdin user_response stty -raw echo # Send the user's input to the bash script send "$user_response\r" exp_continue } # Exit the script when the bash process finishes eof { exit 0 } } }
Step 2: Breakdown of Key Parts
- Shebang:
#!/usr/bin/expect -ftells the system to run this script with the Expect interpreter. - Spawn:
spawn ./script.shlaunches your target bash script and lets Expect monitor its output. - Timeout:
set timeout -1ensures Expect never times out waiting for a prompt (critical for interactive flows). - Auto-Reply Blocks: For each known question, we send a predefined response and use
exp_continueto keep monitoring for the next prompt. - Manual Fallback: The regex
-re {.*\?}catches any unrecognized prompt ending with a question mark. We then pause automation, let the user type a response, and send it to the bash script. - EOF Handling: When your
script.shfinishes running, Expect detects the end-of-file signal and exits cleanly.
Step 3: Run the Script
- Give your bash script execute permissions:
chmod +x script.sh - Do the same for the Expect script:
chmod +x auto_reply.exp - Launch the automation:
./auto_reply.exp
Test It Out
When you run the script:
- It will auto-reply to "Would you like tea ?" and "Would you like car ?"
- When it hits "Would you like cup ?" or "Would you like cake ?", it will prompt you to type a manual response, then continue the flow.
内容的提问来源于stack exchange,提问作者Logicsystem360




