在Mac应用程序中提升管理员权限

7

我正在开发一个简单的应用程序,可以让您快速输入要运行的shell命令。 它的功能很完美,但是有sudo命令的问题。 目前,它会检测sudo命令,然后我尝试让它弹出一个授权窗口,要求用户输入密码,就像在Installer中看到的那样。

以下是一旦检测到sudo命令后的代码:

SFAuthorization *authorization = [[SFAuthorization alloc] initWithFlags:kAuthorizationFlagPreAuthorize rights:NULL environment:kAuthorizationEmptyEnvironment];
if ([authorization obtainWithRight:"com.mycompany.myapplication" flags:kAuthorizationFlagPreAuthorize error:nil]){
    //authorized, now run the command using NSTask.
}else{
    //fail
}

据我所知,这是完全错误的。这只是我从文档中拼凑出来的东西。有任何想法吗?

3个回答

2
您需要使用AuthorizationExecuteWithPrivileges函数,就像这样:

- (IBAction)touch: (id) sender {

  NSString * filepath = [_filepathfield stringValue];
  FILE *commpipe = NULL;
  OSStatus execstatus;


  NSLog(@"file path is %@", filepath);

  char *args[] = {[filepath cString], NULL};


  SFAuthorization * authorization = [SFAuthorization authorization];

  execstatus = AuthorizationExecuteWithPrivileges([authorization authorizationRef],
                                                  "/usr/bin/touch",
                                                  kAuthorizationFlagDefaults,
                                                  args,
                                                  &commpipe);

  if (execstatus == errAuthorizationSuccess) 
    NSlog(@"Toot! It worked");
  else
    NSLog(@"No dice");

}

考虑到BSD是一个脆弱而易怒的花朵,我建议不要让用户以root身份从应用程序中任意执行命令。
/演讲
您示例中的代码是限制自己程序用户功能的开端。例如,您可能有一个只允许特定用户更改保存文件中数据的应用程序。因此,您将在安全数据库'com.mycompany.LibraryApp.AlterData'中创建一个条目,并在用户尝试更改数据时检查其是否具有该权限。但这是一个完全不同的话题...
希望对您有所帮助, -p.

但这不会执行NSTask。有什么想法如何使用特权执行NSTask吗? - Alex Kievsky

2

我知道这是一个很老的问题,但对于那些仍在寻找答案的人,这里有一个解决方法。(它使用AppleScript)

NSAppleScript *script = [[NSAppleScript alloc] initWithSource:@"do shell script \"[YOUR SCRIPT HERE]\" with administrator privileges"];

当然,将[YOUR SCRIPT HERE]替换为您的脚本,并确保按照可可语言转义字符串。请注意,保留HTML标签。
NSDictionary *errorInfo;
[script executeAndReturnError:&errorInfo];

如需进一步解释,请评论。


1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接