Automator is very cool because it will give you a compiled app that can run AppleScript and execute the more powerful Unix shell commands as well. Actually AppleScript gives you this ability too via the do shell script command i.e:
do shell script "mkdir /Library/StartupItems"
What this example shows you:
- How to show a dialog with AppleScript where you can ask for a hidden password that is not visible (not shown) as typed.
- How to run commands in a bash shell with sudo access in Automator.
- How to run bash shell commands in AppleScript with sudo access.
Ok, so now if you are like me, you know the power of Unix shell scripting, you also know it won't be long before you'll need sudo to run one or more commands in your script. Now I did a quick search on the internet to just find some sample code, and in all my searching I found most people have not posted a good solution. Most people in their sample scripts or Automator workflows resorted to storing the password in clear text within the script. Not only is that a security risk, your script is no longer portable and has to be edited for every user. I found responses like
this basically saying it couldn't be done.
Ok, so here's what you do. I created an Automator script, that first runs the following AppleScript (this would also work, just in plain AppleScript without Automator):
on run {input, parameters}
tell application "System Events"
set the_username to do shell script "whoami"
set the_password to "password"
display dialog "You now need to enter the password for the currently logged in account: " & the_username & "
This account must have Administrator access to this computer." default answer "password" buttons {"OK", "Cancel"} default button "OK" with icon 2 with title "Password" with hidden answer
set the_password to text returned of the result
end tell
return {the_password}
end run
Ok in the Automator script, then my next step in Run Shell Script (in bash of course). That script looks like:
exec echo $1 | sudo -v -S;
if [ $? -eq 1 ] then
echo "you are not a sudoer"; else
echo "you are a sudoer"; # replace this with your entire script.
exec echo $1 | sudo -S ls /private/var/root/;
fi
Now all you have to do is put your sudo needing commands inside the else fi block and you're set. If you want to download an Automator script with this code as an example,
click here. BTW if you are running within an AppleScript app you can call sudo like this:
do shell script "sudo ls /private/var/root/" password the_password with administrator privileges