Search code examples
objective-cmacosbashsudonstask

Executing sh file with sudo in OS X gives an error


I've developed an application where I need to run some script under root. Also sh script contains "sudo" commands. For running sh script under root I use STPrivilegedTask class from github: https://github.com/sveinbjornt/STPrivilegedTask

Here how I run a script:

NSString *scriptPath = [[NSBundle mainBundle] pathForResource:@"my_script" ofType:@"sh"];
STPrivilegedTask *task = [[STPrivilegedTask alloc] initWithLaunchPath:scriptPath];
int result = [task launch]; // return error 60031 which means:
//errAuthorizationToolExecuteFailure      = -60031, /* The specified program could not be executed. */

And here is a script I use:

#!/bin/bash
sudo mkdir -p /usr/local/myfolder
sudo su - root -c "launchctl load -F /System/Library/LaunchDaemons/com.mydaemon.daemon.plist"

I use OS X Mavericks 10.9.4

EDIT: After I set "chmod +x my_script.sh" for script it runs script. But now I receive next errors in console:

sudo: no tty present and no askpass program specified
sudo: no tty present and no askpass program specified

Seems that my admin credentials I put didn't applied with script I run. Any ideas how to fix that?


Solution

  • Here are two solutions taken in part from this stackexchange thread, which I can't test because I do not currently own a mac.

    Solution 1: Use OSAScript to run the command in the first place

    #!/bin/bash
    sudo mkdir -p /usr/local/myfolder
    osascript -e "do shell script \"mkdir -p /usr/local/myfolder\" with administrator privileges"
    osascript -e "do shell script \"launchctl load -F /System/Library/LaunchDaemons/com.mydaemon.daemon.plist\" with administrator privileges"
    

    Solution 2: Use OSAScript to prompt for a password and use that with sudo

    #!/bin/bash
    pw = "$(osascript -e 'Tell application "System Events" to display dialog "Password:" default answer "" with hidden answer' -e 'text returned of result' 2>/dev/null)"
    
    echo $pw | sudo -S mkdir -p /usr/local/myfolder
    echo $pw | sudo -S su - root -c "launchctl load -F /System/Library/LaunchDaemons/com.mydaemon.daemon.plist"