I want to secure the execution of a program with a password. How can I ask the user to enter a password without echoing it?
-
1Voting to close as unclear, please specify how you want password input to be different than other inputs. No echoing asked at: stackoverflow.com/questions/3980668/…Ciro Santilli OurBigBook.com– Ciro Santilli OurBigBook.com2016-06-29 21:26:03 +00:00Commented Jun 29, 2016 at 21:26
3 Answers
This command will read into var pw from stdin (with echo disabled):
IFS= read -r -s -p 'Password: ' pw
echo
The last echo adds a newline to the terminal output (otherwise next commands would appear in the same line as the Password: prompt.
Unsetting IFS allows 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).
If you want, you can verify that the above works by running it with a fake password that includes whitespace and then printing the variable's contents into hexdump:
printf '%s' "$pw" | 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.