在Linux Shell脚本中实现自动交互功能有多种方法,以下是几种常用的解决方案:
expect是专门设计用于自动交互的工具,可以模拟用户输入。
#!/usr/bin/expect
spawn your_command
expect "prompt text"
send "your response\r"
expect eof
示例:自动SSH登录
#!/usr/bin/expect
set timeout 30
spawn ssh user@host
expect "password:"
send "your_password\r"
interact
适用于简单的交互场景,将输入直接传递给命令。
your_command << EOF
response1
response2
EOF
示例:自动配置MySQL
mysql -u root -p << EOF
your_password
CREATE DATABASE testdb;
USE testdb;
CREATE TABLE users (id INT, name VARCHAR(20));
EOF
通过管道将输入传递给命令。
echo -e "response1\nresponse2" | your_command
示例:自动回答apt-get安装问题
echo -e "y\n" | sudo apt-get install package
对于只需要重复相同回答的场景。
yes | command_that_asks_confirmation
可以记录交互过程并生成expect脚本。
autoexpect your_command
对于SSH场景,更安全的做法是使用密钥认证而非密码。
ssh-keygen -t rsa
ssh-copy-id user@host
选择哪种方法取决于具体场景的复杂度和安全性要求。对于简单交互,here document或管道可能就足够了;对于复杂交互,expect是更强大的选择。