在 bash 脚本中模拟用户输入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14670716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:18:01  来源:igfitidea点击:

Simulate user input in bash script

bashinputemulationuser-input

提问by Werulz

I am creating my own bash script, but I am stuck at the moment. Basically, the script would be used to automate server setup in CentOS. Some software normally asks the user to type a password. I want the script to put the password that I have generated and stored as a variable instead of asking the user.

我正在创建自己的 bash 脚本,但目前我被卡住了。基本上,该脚本将用于在 CentOS 中自动设置服务器。某些软件通常会要求用户输入密码。我希望脚本将我生成并存储为变量的密码放入而不是询问用户。

When the message "New password:" appears during install, how can I make the script put the value stored in a variable $keyas if the user had typed it, with a bash script?

当安装过程中出现消息“新密码:”时,如何让脚本将值存储在变量中$key,就像用户输入它一样,使用 bash 脚本?

回答by FreudianSlip

You should find the 'expect' command will do what you need it to do. Its widely available. See here for an example : http://www.thegeekstuff.com/2010/10/expect-examples/

您应该会发现 'expect' 命令会做您需要它做的事情。其广泛可用。请参阅此处的示例:http: //www.thegeekstuff.com/2010/10/expect-examples/

(very rough example)

(非常粗略的例子)

#!/usr/bin/expect
set pass "mysecret"

spawn /usr/bin/passwd

expect "password: "
send "$pass"
expect "password: "
send "$pass"

回答by kevoroid

Here is a snippet I wrote; to ask for users' password and set it in /etc/passwd. You can manipulate it a little probably to get what you need:

这是我写的一个片段;询问用户密码并将其设置在 /etc/passwd 中。您可以稍微操纵它以获得您需要的东西:

echo -n " Please enter the password for the given user: "
read userPass
useradd $userAcct && echo -e "$userPass\n$userPass\n" | passwd $userAcct > /dev/null 2>&1 && echo " User account has been created." || echo " ERR -- User account creation failed!"