0

TLDR; I want to read a user input directly from the terminal leaving stdin untouched.

context

I'm writing a shell script that handles user passwords (verifying strength and authenticating other apps). Since the script also reads data from stdin, I can't simply use the good ol' one-liner solution.

read -s -p "Password: " password

If my script used the above method it wouldn't work correctly when the user pipes data to the script from another program.

Then I found out that sudo gets the user password from the terminal device directly, not interfering with stdin... unless told otherwise (with -S flag).

$ man sudo
...
     -S, --stdin
                 Write the prompt to the standard error and read the password from the stan‐
                 dard input instead of using the terminal device.
 -A, --askpass
             Normally, if sudo requires a password, it will read it from the user's ter‐
             minal.  If the -A (askpass) option is specified, a (possibly graphical)
             helper program is executed to read the user's password and output the pass‐
             word to the standard output.  If the SUDO_ASKPASS environment variable is
             set, it specifies the path to the helper program.

So that when I use sudo some_priv_cmd in the script, it can still prompt the user password even though stdin is occupied by some datastream.

question

I'm looking for a program that can prompt the user just like sudo does, and returns (or echoes) the input string. More specifically, the program can be used as SUDO_ASKPASS, and sudo -A should work just like normal sudo.

If such a utility does not exist, can someone provide some clues on how can I implement it? Which library, or function/feature should I be searching for?

my attempts

  • I've tried read -s -p solution in place of SUDO_ASKPASS just to find the feature I'm looking for indeed requires special handling.
  • I'm suspecting the termios library for dealing with terminal-specific tasks, but not sure how to use it.
bivoje
  • 1

0 Answers0