在OS X中使用sudo执行sh文件会出错

时间:2014-09-09 11:52:05

标签: objective-c macos bash sudo nstask

我开发了一个应用程序,我需要在root下运行一些脚本。 sh脚本还包含" sudo"命令。为了在root下运行sh脚本,我使用github中的STPrivilegedTask类: https://github.com/sveinbjornt/STPrivilegedTask

这是我如何运行脚本:

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. */

这是我使用的脚本:

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

我使用OS X Mavericks 10.9.4

编辑: 在我设置" chmod + x my_script.sh"对于脚本,它运行脚本。但是现在我在控制台中收到了下一个错误:

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

似乎我放置的管理员凭据没有应用我运行的脚本。任何想法如何解决?

2 个答案:

答案 0 :(得分:3)

以下是this stackexchange thread部分采用的两种解决方案,我无法测试,因为我目前没有Mac。

解决方案1:使用OSAScript首先运行命令

#!/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"

解决方案2:使用OSAScript提示输入密码并将其与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"

答案 1 :(得分:1)

如果您正确使用STPrivilegedTask,那么该脚本应该已经以root权限运行,因此在这种情况下实际上不需要sudo命令。

你应该使用类似于:

的东西
sudo=
[[ $(id -u) != 0 ]] && sudo=sudo
$sudo <command that would need sudo>

应该可以防止没有tty的错误,这与在GUI应用程序中调用sudo命令有关。