无需交互的 Bash 脚本
我想做以下事情:
我有一个 bash 脚本,它调用一个交互式命令,要求用户输入密码。我想将脚本中的密码指定为变量,并以非交互方式将该变量传递给命令。
I would like to do following:
I have a bash script that calls an interactive command that asks the user for a passphrase. I want to specify the passphrase in the script as a variable, and pass that variable to the command non-interactively.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我相信您想了解expect。该实用程序专为代表用户打字而设计。
假设您的脚本有一个提示(或在需要用户交互之前可靠地出现的一行),expect 可以解析输出,并且当它看到该行(例如“passphrase:”)时,输入您的密码并继续执行脚本。
I believe you would like to look into expect. This utility is designed specifically for typing on behalf of the user.
Assuming your script has a prompt (or a line that dependably appears before user interaction is required), expect can parse the output, and when it sees the line, e.g., 'passphrase:', enter your passphrase and continue execution of the script.
这是一个非常基本的技术。为脚本提供输入文件。如果您不想修改脚本本身,这是一个不错的选择。
我必须使用我自己想象的一个例子。这是一个提示用户输入值的基本脚本,将其称为
scp
:您可以提供一个输入文件,将其称为
input
:然后调用提供
的脚本input
用于脚本的输入,执行以下操作:..或者简洁地:
输出如下所示:
Here is a very basic technique. Provide an input file to the script. It is a good choice if you don't want to modify the script itself.
I have to use an example that I dreamed up myself. Here's a basic script prompting the user for values, call it
scp
:You can provide an input file as such, call it
input
:Then to invoke the script providing
input
for input to the script do this:..or alternatively and concisely:
The output looks like this:
假设您的脚本是这样的(genrsa.sh):
通常,如果您执行 genrsa.sh 文件,它将要求输入文件名和密码两次。就像这样:
您想要以某种方式更改脚本,以便可以将密码作为参数传递。所以它不会等待您输入。您将像这样使用它:
为此,您必须将脚本更改为类似的内容(genrsa2.sh):
Lets assume that your script is this(genrsa.sh):
Normally, if you execute the genrsa.sh file it will ask for a file name and passphrase twice. Like that:
You want to change the script in a way so you can pass your passphrase as a parameter. So it won't wait for you to type. You will use it like that:
To do that, you have to change your script to something like that(genrsa2.sh):
其中 2 (也可能是第一个参数)是第二个位置参数,“defaultvalue”是变量在您未指定任何值的情况下采用的值。
Where 2 (could be the 1st parameter too) is the second positional parameter and "defaultvalue" is the value the variable takes in case you don't specify any value.