1

For the purposes of a bash script I need to prompt the user for the sudo password if it hasn't been entered yet (and if the user doesn't have sudo privileges at the time they run the script).

I first request the password with dialog password bog, and then feed it to sudo, like so:

SUDOPWD=$(dialog --title "Password" --clear --passwordbox "Enter your sudo password" 10 30  2>&1 > /dev/tty)

echo ${SUDOPWD} | sudo -Sn -v

But, alas, that does not work! Apparently -S (read password from stdin), and -n (non-interactive sudo) are not compatible! With -n present, the password being fed to sudo is ignored (and so no elevation occurs), and without it sudo prompts for re-entry if an incorrect password was entered.

Is there any way to validate sudo password without re-prompting for it if it's not the right one?

Inevitably someone will point out that one should not be re-inventing the wheel, and just use sudo's provided facility, or that feeding a password to sudo via a pipe has security implications. I'm aware of those factors, and still would like to do what I'm outlining above is it is possible. I also don't want to enter the commands in /etc/sudoers, recompile sudo (as the script should be somewhat portable), or disable sudo password prompt in general (just in this script).

I'm working on this on Ubuntu 16.04.

2
  • I suppose I can leave the -n switch out, and redirect all output to null.. echo ${SUDOPWD} | sudo -S -v &> /dev/null. It seems to work (if sudo prompt occurs, it doesn't seem to be holding things up). It's kind of a kludge, though.. any cleaner solutions? – Ville Feb 18 '17 at 5:29
  • Related: askubuntu.com/questions/515292/… – Kusalananda Feb 18 '17 at 7:57
3

You can determine if the user is already authenticated with sudo -vn 2>/dev/null

If they're not, you can use the following to ask for a password and pipe it into sudo.

printf '%s\n' "$(dialog --output-fd 1 --passwordbox "Enter password:" 10 30)" | \
sudo -Svp ''
  • --output-fd 1 tells dialog to output to STDOUT
  • printf is used to append a newline to the input, which is required for sudo -S
  • sudo -p '' uses '' as the password prompt message, hiding it

If you're cool with storing your output in a variable, you can just printf '%s\n' "${SUDOPWD}" and that should do it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.