我想从我的Cocoa项目中运行以下命令。(隐藏聚光灯图标)
sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search我找到了两种方法来调用命令并获得以下输出
1)使用NSTask
NSTask *writeTask = [[NSTask alloc] init];
[writeTask setLaunchPath:@"/bin/chmod"];
[writeTask setArguments: @[@"755",@"/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search"]];
[writeTask launch];
>>chmod: Unable to change file mode on /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search: Operation not permitted2)喉管
NSString *command = @"sudo chmod 755/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search";
fp = popen([command UTF8String], "r");
>>sudo: no tty present and no askpass program specified我还没有找到一种方法,如何运行这些超级用户模式。如何提示用户输入密码,并最终以所需权限运行此命令?
发布于 2013-11-19 06:32:01
使用Apple Script Editor编写下面的apple脚本,并将其保存在.scpt文件中。
do shell script "sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search" with administrator privileges现在将此文件添加到包中。
然后,要从程序中调用此脚本,请使用以下代码:
- (void) runEmbeddedScriptFile: (NSString*)fileName
{
NSString* path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"scpt"];
NSURL* url = [NSURL fileURLWithPath:path];
NSDictionary* errors = [NSDictionary dictionary];
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
[appleScript executeAndReturnError:nil];
[appleScript release];
}这将提示用户的密码请求。
发布于 2013-11-19 02:40:21
在10.7之前,您可以使用AuthorizationExecuteWithPrivileges()执行具有特权的任务。然而,这在10.7中已被否决,苹果建议使用ServiceManagement框架来执行特权任务。
SMJobBless演示如何安全地安装执行特权操作的助手工具,以及如何将该工具与调用该工具的应用程序关联。 SMJobBless使用MacOSXv10.6雪豹中引入的ServiceManagement.framework。 对于雪豹来说,这是管理Mac上权限提升的首选方法,应该使用它来代替早期的方法,比如BetterAuthorizationSample或直接调用AuthorizationExecuteWithPrivileges。
苹果的样本代码
发布于 2013-11-19 11:09:41
您需要使用授权服务获取根权限,然后使用sys/stat.h中的chmod()
https://stackoverflow.com/questions/20061526
复制相似问题