将授权服务与 NSTask 一起使用

Posted

技术标签:

【中文标题】将授权服务与 NSTask 一起使用【英文标题】:Using Authorization Services with NSTask 【发布时间】:2014-08-01 18:09:11 【问题描述】:

好的,我正在使用 NSTask 运行需要以管理员权限运行的 shell 脚本。我正在使用这个问题的一些代码:NSTask and AuthorizationCreate。 这是我目前拥有的:

//Authorization Create
AuthorizationRef myAuthorizationRef;
OSStatus myStatus;
myStatus = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment,
                                kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed , &myAuthorizationRef);
AuthorizationItem myItems[1];

myItems[0].name = "com.myOrganization.myProduct.myRight1";
myItems[0].valueLength = 0;
myItems[0].value = NULL;
myItems[0].flags = 0;

AuthorizationRights myRights;
myRights.count = sizeof (myItems) / sizeof (myItems[0]);
myRights.items = myItems;

AuthorizationFlags myFlags;
myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagExtendRights;

myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights,
                                    kAuthorizationEmptyEnvironment, myFlags, NULL);

if (myStatus==errAuthorizationSuccess)

    NSString *path = [[NSBundle mainBundle] pathForResource:@"kandorBackup" ofType:@"sh"];

    NSPipe *outputPipe = [NSPipe pipe];
    readHandle = [outputPipe fileHandleForReading];
    inData = nil;
    returnValue = nil;

    NSTask *task = [[NSTask alloc] init];
    [task setLaunchPath:path];
    [task setArguments:[NSArray arrayWithObjects:login, selectedDrive, rsyncFinalFlags, nil]];
    [task setStandardOutput:outputPipe];
    [readHandle waitForDataInBackgroundAndNotify];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(recievedData:)
                                                 name:NSFileHandleDataAvailableNotification

                                               object:nil];
    [task launch];

myStatus = AuthorizationFree (myAuthorizationRef,
                              kAuthorizationFlagDestroyRights);

执行此操作时,系统会提示我输入管理员用户名和密码,但随后任务会像往常一样运行,无需提升权限。让 NSTask 实际使用授权我缺少什么?

【问题讨论】:

【参考方案1】:

在这里,您只是获得了一个 AuthorizationRef 并且什么都不做,只是获得授权不会使您的可执行文件具有特权运行。您可以使用 ref 启动使用 SMJobSubmit 嵌入到应用程序中的可执行文件,并且在该可执行文件中,您可以使用具有提升权限的 NSTask。下面是一些示例代码,解释了它是如何工作的:http://www.stairways.com/blog/2012-08-06-smjobsubmit

【讨论】:

以上是关于将授权服务与 NSTask 一起使用的主要内容,如果未能解决你的问题,请参考以下文章

是否会被 MAS 拒绝使用 NSTask 和 open 命令打开 Safari 或其他应用程序

NSTask 启动路径错误 [重复]

NSBundle 中的 NSTask

使用包含文件的第一级文件夹的 NSTask 创建 zip 存档

Swift NStask 函数

NSTask 源码中有趣的地方