How to add Root privileges to my OSX application?

前端 未结 1 1072
名媛妹妹
名媛妹妹 2021-01-01 02:14

I made an application as root user, it worked perfectly(in root user). When I try same application with a standard user it didn\'t work out. Then I get to know that I need r

相关标签:
1条回答
  • 2021-01-01 02:32

    I use this code to get the root privilege for my application. I made a new project to use this code.

    // 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.
        // http://developer.apple.com/qa/qa2001/qa1172.html
        status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
                                     kAuthorizationFlagDefaults, &authorizationRef);
        if (status != errAuthorizationSuccess)
            NSLog(@"Error Creating Initial Authorization: %d", status);
    
        // 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);
    
        NSLog(@"\n\n** %@ **\n\n", @"This command should work.");
        char *tool = "/sbin/dmesg";
        char *args[] = {NULL};
        FILE *pipe = NULL;
    
        status = AuthorizationExecuteWithPrivileges(authorizationRef, tool,
                                                    flags, args, &pipe);
        if (status != errAuthorizationSuccess)
            NSLog(@"Error: %d", status);
    
        // 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.
        // http://developer.apple.com/documentation/Security/Conceptual/authorization_concepts/02authconcepts/chapter_2_section_7.html
        status = AuthorizationFree(authorizationRef, kAuthorizationFlagDestroyRights);
    
    0 讨论(0)
提交回复
热议问题