cocoa获取管理员权限

来源:互联网 发布:网络正常魔域连接错误 编辑:程序博客网 时间:2024/06/05 00:10
下面的代码提高权限来删除指定文件


+ (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);

        returnNO;

    }

    // 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);

        returnNO;

    }

    // use rm tool with -rf

    char *tool ="/bin/rm";

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

    FILE *pipe =NULL;

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

    if (status !=errAuthorizationSuccess)

    {

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

        returnNO;

    }

    // 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);

    returnYES;

}


0 0
原创粉丝点击