我正在尝试使用NSTask运行以下命令:
$sudo launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist下面是我使用的代码:
NSTask *server = [NSTask new];
[server setLaunchPath:@"/bin/launchctl"];
[server setArguments:[NSArray arrayWithObjects:@"load",@"com.devdaily.crontabtest.plist",nil]];
[server setCurrentDirectoryPath:@"/Users/admin/Library/LaunchAgents/"];
NSPipe *outputPipe = [NSPipe pipe];
[server setStandardInput:[NSPipe pipe]];
[server setStandardOutput:outputPipe];
[server launch];
[server waitUntilExit]; // Alternatively, make it asynchronous.
[server release];但是,由于sudo命令,它不能工作。我该如何解决这个问题呢?
发布于 2013-03-24 19:30:10
不幸的是,你不能。因为没有办法输入密码。
但是,您仍然可以通过使用NSAppleScript而不是NSTask来运行您的bash命令:编写如下applescript:
do shell script [your command] with administrator privileges
系统将要求您提供管理员密码。
示例:
NSDictionary *error = [NSDictionary new];
NSString *script = @"do shell script \"launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist\" with administrator privileges";
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
if ([appleScript executeAndReturnError:&error]) {
NSLog(@"success!");
} else {
NSLog(@"failure!");
}发布于 2013-03-24 19:59:12
阅读苹果的Secure Coding Guide,并遵循Elevating Privileges Safely的推荐。
换句话说,不要使用sudo或类似的东西。使用SMJobBless()安装并启用启动代理。另请参阅SMJobBless sample project。
https://stackoverflow.com/questions/10501067
复制相似问题