How to use sudo inside of a Run Script build phase in Xcode 4?

One solution is to place the sudo password in an executable shell script like the following:

#!/bin/bash
echo thesudopassword

This shell script might be called password.sh

Then, setup the environment variable SUDO_ASKPASS=password.sh

Once this is setup, the -A option can be passed to sudo. This option uses the ASKPASS program to obtain the sudo password. The ASKPASS program need only write the password to stdout.

So, for example,

sudo -A ditto -V /tmp/testserver.dst /

This is obviously a rather insecure solution, but it does work.


After much searching I found the following solution.

https://forum.juce.com/t/build-script-for-automatically-moving-built-aus-into-components-folder-xcode/13112

Summary

  1. Create a keychain and store your admin password in the keychain
  2. Create a script which uses /usr/bin/security to access the password In your run script,
  3. Set the ASK_PASS env variable and use the -A option with sudo

Two ideas that haven't been suggested yet, both of which are probably better/safer than the currently accepted answer:

First option would be to put the part of the script that needs to be run as root in a script file (.sh or something), and then make it setuid as root: chmod go-w,+sx scriptfile, sudo chown root scriptfile. This means that script will automatically run as root, which avoids you needing to authenticate to run it (just to change it). As long as its operation isn't subject to user input, this should be quite safe. (Of course, if you make a script that takes an input argument and deletes it or runs it, or does most anything else with it, that would not be safe.)

Second option would be to use applescript (possibly via osascript). Applescript allows you to do shell script "sudo command goes here" with administrator privileges, which will pop up a graphical dialog asking for a password.

The first of these options would be good for an automated environment, though it might not deal well with (for example) being checked into an SCM, or being sent to another user. The second option would work better with that, but requires a password input every time, so doesn't work as well for an automated build script.


Another solution to this problem is to modify sudoers file and add your account to it and state that you should never be asked for the sudo password. To accomplish this is fairly straightforward:

run:

sudo visudo

In the User privilege specification section add a line that looks like

youraccountname ALL=(ALL) NOPASSWD: ALL

Of course, this can be a dangerous thing to do, so be careful. I would suggest reading the man page for sudoers and visudo before going this route.