在OSX中用sudo执行sh文件会出现错误



我开发了一个应用程序,需要在根目录下运行一些脚本。同样,sh脚本包含"sudo"命令。为了在根目录下运行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

我的管理员凭据似乎没有应用到我运行的脚本中。有什么办法解决的吗?

这里有两个部分来自这个stackexchange线程的解决方案,我无法测试,因为我目前没有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"

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

你应该使用类似于的东西

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

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

相关内容

最新更新