cocoa获取管理员权限

下面的代码提高权限来删除指定文件


+ (BOOL)removeFileWithElevatedPrivilegesFromLocation:(NSString *)location

{

    // Create authorization reference

    OSStatus status;

    AuthorizationRef authorizationRef;

    // AuthorizationCreate and pass NULL as the initial

    // AuthorizationRights set so that the AuthorizationRef gets created

    // successfully, and then later call AuthorizationCopyRights to

    // determine or extend the allowable rights.

    //  CodeGo.net

    status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagDefaults, &authorizationRef);

    if (status != errAuthorizationSuccess)

    {

        NSLog(@"Error Creating Initial Authorization: %d", status);

        return NO;

    }

    // kAuthorizationRightExecute == "system.privilege.admin"

    AuthorizationItem right = {kAuthorizationRightExecute, 0, NULL, 0};

    AuthorizationRights rights = {1, &right};

    AuthorizationFlags flags = kAuthorizationFlagDefaults | kAuthorizationFlagInteractionAllowed |

    kAuthorizationFlagPreAuthorize | kAuthorizationFlagExtendRights;

    // Call AuthorizationCopyRights to determine or extend the allowable rights.

    status = AuthorizationCopyRights(authorizationRef, &rights, NULL, flags, NULL);

    if (status != errAuthorizationSuccess)

    {

        NSLog(@"Copy Rights Unsuccessful: %d", status);

        return NO;

    }

    // use rm tool with -rf

    char *tool = "/bin/rm";

    char *args[] = {"-rf", (char *)[location UTF8String], NULL};

    FILE *pipe = NULL;

    status = AuthorizationExecuteWithPrivileges(authorizationRef, tool, kAuthorizationFlagDefaults, args, &pipe);

    if (status != errAuthorizationSuccess)

    {

        NSLog(@"Error: %d", status);

        return NO;

    }

    // The only way to guarantee that a credential acquired when you

    // request a right is not shared with other authorization instances is

    // to destroy the credential. To do so, call the AuthorizationFree

    // function with the flag kAuthorizationFlagDestroyRights.

    //  CodeGo.net

    status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);

    return YES;

}


阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页