I have a script that automates a process that needs access to a password protected system. The system is accessed via a command-line program that accepts the user password as an argument.
I would like to prompt the user to type in their password, assign it to a shell variable, and then use that variable to construct the command line of the accessing program (which will of course produce stream output that I will process).
I am a reasonably competent shell programmer in Bourne/Bash, but I don't know how to accept the user input without having it echo to the terminal (or maybe having it echoed using '*' characters).
Can anyone help with this?
You can also prompt for a password without setting a variable in the current shell by doing something like this:
For instance:
You can add several of these prompted values with line break, doing this:
The
-s
option ofread
is not defined in the POSIX standard. See http://pubs.opengroup.org/onlinepubs/9699919799/utilities/read.html. I wanted something that would work for any POSIX shell, so I wrote a little function that usesstty
to disable echo.This function behaves quite similar to the
read
command. Here is a simple usage ofread
followed by similar usage ofread_secret
. The input toread_secret
appears empty because it was not echoed to the terminal.Here is another that uses the
-r
option to preserve the backslashes in the input. This works because theread_secret
function defined above passes all arguments it receives to theread
command.Finally, here is an example that shows how to use the
read_secret
function to read a password in a POSIX compliant manner.First of all, if anyone is going to store any password in a file, I would make sure it's hashed. It's not the best security, but at least it will not be in plain text.
First, create the password and hash it:
Now, create your program to use the hash. In this case, this little program receives user input for a password without echoing, and then converts it to hash to be compared with the stored hash. If it matches the stored hash, then access is granted: