Home » Java » How to setup a SUDO_ASKPASS environment variable?

How to setup a SUDO_ASKPASS environment variable?

Posted by: admin December 28, 2021 Leave a comment


What does setting up a SUDO_ASKPASS environment variable mean? How do you do it? Where do I declare it?

I am trying to use a shell script to shutoff my computer after a couple of minutes and initiate this script with java.


So I am not sure I’d use $SUDO_ASKPASS for this. Basically the value of $SUDO_ASKPASS is to be an executable that will spit your password to standard out when invoked. So, if your password was ‘foo’, you could write a shell script as:

echo 'foo'

and place it in ~/bin/pw.sh. Then you would set the environment variable and execute the command as so:

SUDO_ASKPASS=${HOME}/bin/pw.sh sudo shutdown -h now

that example assumes that you’re on Darwin; shutdown behaves differently on different operating systems.

A more intelligent way of doing this (and more secure) is to use the NOPASSWD argument in /etc/sudoers. We would add a line like this:

jane ALL=NOPASSWD: /sbin/shutdown

This again assumes you’re on a Mac. And that your name is Jane. Change that. This way sudo will not ask for a password when you issue the command /sbin/shutdown. The command to (properly) edit sudoers is visudo.


Mac-specific answer:

If you don’t want your clear-text password in some file you can also invoke a GUI prompt to enter the password manually whenever something like sudo -A ... is called. To do so create a binary with the following content (taken from this answer):

pw="$(osascript -e 'Tell application "System Events" to display dialog "Password:" default answer "" with hidden answer' -e 'text returned of result' 2>/dev/null)" && echo "$pw"

You can put it for example in a file called ~/bin/pw.sh. Then make it executable by executing chmod +x ~/bin/pw.sh.

Finally set the environment variable to point to this file. Therefore put the following into ~/.bashrc (or ~/.zshrc if you use Z shell):


Finally test everything by executing source ~/.bashrc (or source ~/.zshrc) and then sudo -A ls.