Run UNIX commands in an AppleScript

Leopard Logo If you want to easily encapsulate a shell script or a UNIX command in an AppleScript, but that command must be executed as root (through a sudo), just do the following (all one line):

do shell script "unix_command" password "your_password" with administrator privileges

where unix_command is the actual command you want to execute. In my case, this was to set the Sharing hostname to match the actual DNS hostname of the computer, which looked like this:

do shell script "sudo scutil --set ComputerName `hostname`" password "NoWayJose" with administrator privileges

By the way, if you do intend to set the Sharing name to the computer’s hostname, make sure to include the backticks (located under the ~ sign at the top left of most keyboards) around the word hostname, otherwise you’ll just name your computer ‘hostname’ rather than its DNS name.

It’s important to note that this a) leaves your password in the script, and b) runs silently. If you just want to be prompted for a password, add the following lines before and after your script, like this:

tell application "Terminal"
do script "sudo scutil --set ComputerName `hostname`"
end tell

This will launch Terminal, which will then prompt you for your password in order to sudo.

StackOverflow

Sponsored Links

Leave A Reply

Comments

No comments yet, be the first to add one!