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: http://stackoverflow.com/questions/3980668/how-to-get-a-password-from-a-shell-script-without-echoing – Ciro Santilli Путлер Капут 六四事 Jun 29 '16 at 21:26
3 Answers
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.
- 1,722
- 11
- 17
- 17,806
- 3
- 40
- 57
-
3Are there any disadvantages if I used this instead of the accepted answer? – Tristian Oct 19 '12 at 01:46
-
7@Triztian yes, the above will probably only work in Bash. The accepted answer should work on most (all?) shells. – jberryman Oct 22 '12 at 14:53
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.
- 92,791
- 27
- 183
- 258
-
2One might precompute the checksum of the password and store *it* in the script instead of the plaintext and test the checksum of the input against that. It can still be broken, though, but less easily. – Dennis Williamson Apr 16 '10 at 18:11
-
1In which case you just simply copy the script to somewhere you have write permission, and remove the check. – Martin Beckett Apr 16 '10 at 18:21