How to authenticate a shell script with the OS X GUI

NewTerminalIconXWhen you run various commands and scripts in OS X, you may need to first authenticate the actions you are taking as administrator. While some commands include options for providing authentication, generally you will run the “sudo” command as a precursor to your desired one, in order to promote the desired one to run with full administrative access privileges.

If you use “sudo,” you will still be working within the text-based environment of the Terminal, where you will see a prompt for your password and then not see any indication of the password as you type it. This is understood by those who are familiar with the Terminal; however, if you are writing a script that may require non-familiar users to authenticate, or if you just wish to use a cleaner looking interface, then you can have OS X authenticate the script using a standard password entry OS X dialogue box.

To do this you, can wrap your desired command in a small bit of AppleScript code, that will invoke the OS X GUI. In the following line, the command or script “some-command” will be executed after you authenticate:

do shell script "some-command" with administrator privileges

However, this is pure AppleScript and will require you use the Script Editor tool (in Applications > Utilities) or Automator to execute your script. These approaches are good for many purposes, but if you wish to run a script using this authentication approach in the Terminal, then you need to add another scripting layer to execute the applescript. In the following command, the “osascript” Terminal utility will run the quoted AppleScript code, which as noted above, in turn will authenticate and run the internal command. Note the internal slashes “escape” the internal quotes so they do not prematurely close the outside quotes.

osascript -e "do shell script \"some-command\" with administrator privileges"

While you can run some complex commands and programs in authenticated form using this method, it may be best to use this for running an entire script, as opposed to individual commands. This is especially true given the layering of scripting languages and subsequent requirement for escaping quotes and other characters may become complicated.

3 thoughts on “How to authenticate a shell script with the OS X GUI

  1. Strod

    As an alternative to using backslashes to escape the inner set of double quotes, you can use single quotes for the outer set:

    osascript -e ‘do shell script “some-command” with administrator privileges’

  2. giuseppe1111

    osascript -e ‘do shell script “some-command” user name “your name” password “yourpass” with administrator privileges’

    will prevent the system from asking user password

    1. Jack Wilson

      Use caution with the solution suggested by giuseppe1111 because it leaves your credentials on disk in plain text.

Comments are closed.