How to make bash script ask for a password?
I want to secure the execution of a program with a password.
How do I do that in bash?
stty_orig=`stty -g` # save original terminal setting.
stty -echo # turn-off echoing.
read passwd # read the password
stty $stty_orig # restore terminal setting.
This command will read into var pwd from stdin (with echo disabled):
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)
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.
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.
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.
链接地址: http://www.djcxy.com/p/4370.html上一篇: 回声“在OS X上做
下一篇: 如何让bash脚本请求密码?