如何让 bash 脚本要求输入密码?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2654009/
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 19:11:54  来源:igfitidea点击:

How to make bash script ask for a password?

bashpasswords

提问by Debugger

I want to secure the execution of a program with a password.

我想用密码保护程序的执行。

How do I do that in bash?

我如何在 bash 中做到这一点?

回答by Jürgen H?tzel

This command will read into var pwdfrom stdin (with echo disabled):

此命令将从 stdin读入 var pwd(禁用回显):

IFS= read -s  -p Password: pwd

Unsetting IFS will allow for leading and trailing whitespace in passwords (which may be supported in some environments, so best to support it during your script's input of the user credentials)

取消设置 IFS 将允许密码中的前导和尾随空格(在某些环境中可能支持,因此最好在脚本输入用户凭据期间支持它)

To validate leading/trailing whitespace is handled appropriately you can use:

要验证前导/尾随空格是否得到适当处理,您可以使用:

echo -n "$pwd" | hexdump -C

Note: don't use with real passwords as it dumps to the console!

注意:不要使用真实密码,因为它会转储到控制台!

HT: Ron DuPlain for this additional information on IFS unsetting.

HT:Ron DuPlain 提供了有关 IFS 取消设置的附加信息。

回答by codaddict

stty_orig=$(stty -g) # save original terminal setting.
stty -echo           # turn-off echoing.
IFS= read -r passwd  # read the password
stty "$stty_orig"    # restore terminal setting.

回答by Martin Beckett

If you need to grab a passwd to supply as a paramter to a program, then unicorns advice to just turn off the echo is good.
Having a passwd check in the script doesn't work - if the user can execute the bash script they also have permission to read it and see the passwd.

如果您需要获取 passwd 作为参数提供给程序,那么 unicorns 建议关闭回声是好的。
在脚本中进行密码检查不起作用 - 如果用户可以执行 bash 脚本,他们也有权阅读它并查看密码。

If you want to only allow people with a passwd to run a program then the secure way is to create a new user account that owns the program and have a script that uses 'sudo' to run the program as that user - it will prompt for the users passwd in a secure way.

如果您只想允许拥有密码的人运行程序,那么安全的方法是创建一个拥有该程序的新用户帐户,并拥有一个使用“sudo”以该用户身份运行该程序的脚本 - 它会提示您用户以安全的方式密码。