Keywords: non-interactive scripting | argument passing | Expect automation
Abstract: This article explores various techniques for passing arguments to interactive Bash scripts in non-interactive environments. It begins with basic input redirection methods, including pipes, file redirection, Here Documents, and Here Strings, suitable for simple parameter passing scenarios. The focus then shifts to the Expect tool for complex interactions, highlighting its ability to simulate user input and handle dynamic outputs, with practical examples such as SSH password automation. The discussion covers selection criteria, security considerations, and best practices, providing a comprehensive reference for system administrators and automation script developers.
Introduction
In automation script development and system administration, it is often necessary to invoke programs or scripts originally designed for interactive use. These programs typically use the read command or other interactive input mechanisms to obtain user parameters, such as confirmation actions (yes/no options), password entry, or multi-step configurations. However, in non-interactive environments (e.g., cron jobs, CI/CD pipelines, or batch processing scripts), manual input of these parameters is not feasible. Therefore, developers need to employ technical means to pass arguments programmatically to these interactive programs, enabling automated execution.
Basic Input Redirection Methods
For simple interactive scripts where input order is fixed and no dynamic output handling is required, Bash's built-in input redirection mechanisms can be used. These methods pass arguments via standard input (stdin), simulating user keyboard input.
Pipe Passing
Use a pipe to output a predefined sequence of arguments via the echo command and pass them to the interactive program. For example:
echo "yes
no
maybe" | your_programThis method is suitable for scenarios with a limited number of arguments in a fixed order. Each argument is separated by a newline, and the program reads them sequentially. Note that if the program output includes prompts or requires conditional branching, the pipe method may not handle it correctly, as it only passes data unidirectionally.
File Redirection
Pre-write arguments to a file and then read from the file via input redirection. For example:
your_program < answers.txtwhere the answers.txt file contains multiple lines of arguments. This method facilitates managing large numbers of arguments or scenarios requiring reuse, but it similarly lacks the ability to handle dynamic interactions.
Here Document
Here Document allows embedding multi-line text directly in a script as input. For example:
your_program << ANSWERS
yes
no
maybe
ANSWERSThis method improves code readability, especially for hardcoding parameters in scripts. The label (e.g., ANSWERS) defines the start and end of the input block, with all content until the end label passed to the program.
Here String
Here String is a concise variant of Here Document, suitable for single or multi-line arguments. For example:
your_program <<< $'yes\nno\nmaybe\n'Using the $'...' syntax handles escape characters like newlines (\n). This method is ideal for shorter arguments that need to be inline.
Expect Tool: Handling Complex Interactions
When interactive programs involve dynamic output, conditional branching, or security restrictions (e.g., SSH prohibiting password piping via pipes), basic input redirection methods may fail. In such cases, the expect tool provides a more robust solution. expect is a Tcl-based automation tool specifically designed to simulate user interaction with interactive programs.
Core Functions of Expect
expect controls the interaction process programmatically via scripts. Its core functions include:
- Pattern Matching: Use the
expectcommand to wait for specific patterns in program output (e.g., prompts). - Sending Responses: Use the
sendcommand to send input to the program, simulating keystrokes. - Timeout Handling: Set timeout durations to prevent indefinite waiting.
- Conditional Branching: Dynamically select responses based on program output, enabling complex logic.
For example, a simple Expect script might look like:
#!/usr/bin/expect
set timeout 10
expect "Enter your name:"
send "John\n"
expect "Enter password:"
send "secret123\n"
expect eofThis script waits for the program output "Enter your name:" then sends "John", followed by waiting for a password prompt and sending the password.
Practical Application: SSH Password Automation
SSH clients typically prohibit password passing via pipes for security reasons, to prevent password leakage. Using expect can bypass this restriction, safely automating SSH logins. For example:
#!/usr/bin/expect
set host "example.com"
set user "admin"
set password "mypassword"
expect "password:"
send "$password\n"
expect "$ "
send "ls -la\n"
expect eofThis script automatically logs into a remote host and executes commands without manual password entry. Through pattern matching, it can adapt to different prompt formats.
Advantages and Limitations of Expect
Advantages:
- Handles Dynamic Interactions: Can adjust input based on program output, adapting to complex scenarios.
- Cross-Platform Support: Expect is available on various Unix-like systems, including Linux and macOS.
- Scriptable Control: Supports variables, loops, and conditional statements for flexible automation.
Limitations:
- Learning Curve: Requires learning Tcl syntax and Expect-specific commands.
- Maintenance Cost: Scripts may need updates if program output changes.
- Security: Hardcoding passwords in scripts can pose risks; use keys or environment variables instead.
Method Selection and Best Practices
When selecting a parameter passing method, consider the following factors:
- Interaction Complexity: Use basic redirection for simple linear input; use Expect for dynamic interactions.
- Security: Avoid hardcoding sensitive information in scripts; use encrypted storage or environment variables.
- Maintainability: Prefer highly readable methods like Here Document and add comments.
- Error Handling: Set timeouts and error catching in Expect scripts to prevent hangs.
For example, if a script needs to handle multiple yes/no confirmations, use a Here Document:
./interactive_script.sh << CONFIRMATIONS
yes
no
yes
CONFIRMATIONSFor scenarios requiring input decisions based on output, such as automated configuration tools, Expect is a more suitable choice.
Conclusion
Non-interactively invoking interactive programs is a common requirement in automation tasks. Basic input redirection methods (pipes, file redirection, Here Documents, and Here Strings) are suitable for simple scenarios, offering quick solutions. For complex interactions, especially those involving dynamic output or security restrictions, the expect tool provides powerful programming capabilities to simulate user behavior and achieve high automation. In practice, select the appropriate method based on specific needs and follow best practices for security and maintainability. By combining these techniques, developers can effectively integrate interactive scripts into automated workflows, enhancing system administration efficiency.