Wednesday, September 9, 2015

Executing shellscript with administrator (sudo) privileges (GUI) in Mac OSX using AppleScript

You created an executable shellscript that requires sudo or admin privileges in Mac OSX to do something like install printers, change DNS server... It's not difficult, you just need to open the terminal, grant the script file the executable permission, then run it. But the thing is the terminal interface may scare the shit out of a normal user. What can you do about that? OK, AppleScript is your savior.

Write a wrapper script using AppleScript to call your genius shell. With the AppleScript you can popup a beautiful window (GUI) asking for administrator password. Here is an example:

#! /usr/bin/bash

sudo networksetup -setdnsservers Wi-Fi

Basically, my example do the following:

1. Upload your shellscript somewhere public that allow you to download the script using curl. For example:

2. Using AppleScript to grant executable privileges to the shellscript with "with administrator privileges":

do shell script "chmod +x ~/Desktop/" with administrator privileges

With "with administrator privileges", a popup window will show up and ask for your administrator password.

3.  Run the script with administrator privileges:

do shell script "~/Desktop/" with administrator privileges

Pretty neat!