Take the 2-minute tour ×
Ask Different is a question and answer site for power users of Apple hardware and software. It's 100% free, no registration required.

This problem has ben bugging me for a while now.

Every now and then, I need to write a script file that should execute sudo commands. I do not necessarily know in advance that I will run as sudo so I am sure there is a way to open a nice graphical interface (such as the one popping up when installing software) but how ?

The man sudo says:

-A          Normally, if sudo requires a password, it will read it from the current terminal.  If the -A (askpass) option is specified, a (possibly
            graphical) helper program is executed to read the user's password and output the password to the standard output.  If the SUDO_ASKPASS
            environment variable is set, it specifies the path to the helper program.  Otherwise, the value specified by the askpass option in
            sudoers(5) is used

So I am pretty sure the solution resides in that -A and SUDO_ASKPASS tuple however I've managed to find what to put into those.

share|improve this question
1  
In Linux these would be handled by front-ends like gtksudo or kdesudo. I don't know what there is on the OS-X side of things, but I assume you are looking for something along those lines. –  Caleb Aug 29 '11 at 13:24

2 Answers 2

up vote 11 down vote accepted

OS X doesn't have an entirely clean way to do this, but there are a few ways to fake it. First, AppleScript has a good way to do sudo-ish things based on a graphical authentication, and you can use that:

osascript -e "do shell script \"stufftorunasroot\" with administrator privileges"

You can also use that mechanism to set the sudo timestamp, and then use the regular sudo (within the 5-minute timeout window) to do things:

osascript -e "do shell script \"mkdir -p /var/db/sudo/$USER; touch /var/db/sudo/$USER\" with administrator privileges" && \
    sudo stufftorunasroot

Finally, you can use AppleScript to prompt for a password, then pass that to sudo:

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" | sudo -S stufftorunasroot
share|improve this answer
    
waited for so long to have that thanks for this great tip –  apouche Aug 30 '11 at 7:32

OS X doesn't come with a graphical front-end for sudo but you'll find cocoasudo or macsudo helpful.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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