• 使用applescript脚本方式以管理员权限运行


    - (BOOL) runProcessAsAdministrator:(NSString*)scriptPath
                         withArguments:(NSArray *)arguments
                                output:(NSString **)output
                      errorDescription:(NSString **)errorDescription {

        NSString * allArgs = [arguments componentsJoinedByString:@" "];
        NSString * fullScript = [NSString stringWithFormat:@"%@ %@", scriptPath, allArgs];

        NSDictionary *errorInfo = [NSDictionary new];
        NSString *script =  [NSString stringWithFormat:@"do shell script "%@" with administrator privileges", fullScript];

        NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script];
        NSAppleEventDescriptor * eventResult = [appleScript executeAndReturnError:&errorInfo];

        // Check errorInfo
        if (! eventResult)
        {
            // Describe common errors
            *errorDescription = nil;
            if ([errorInfo valueForKey:NSAppleScriptErrorNumber])
            {
                NSNumber * errorNumber = (NSNumber *)[errorInfo valueForKey:NSAppleScriptErrorNumber];
                if ([errorNumber intValue] == -128)
                    *errorDescription = @"The administrator password is required to do this.";
            }

            // Set error message from provided message
            if (*errorDescription == nil)
            {
                if ([errorInfo valueForKey:NSAppleScriptErrorMessage])
                    *errorDescription =  (NSString *)[errorInfo valueForKey:NSAppleScriptErrorMessage];
            }

            return NO;
        }
        else
        {
            // Set output to the AppleScript's output
            *output = [eventResult stringValue];

            return YES;
        }
    }

        NSString * output = nil;
        NSString * processErrorDescription = nil;
        BOOL success = [self runProcessAsAdministrator:@"/usr/bin/id"
                        withArguments:[NSArray arrayWithObjects:@"-un", nil]
                               output:&output
                                errorDescription:&processErrorDescription
                      asAdministrator:YES];

        if (!success) // Process failed to run
        {
             // ...look at errorDescription
        }
        else
        {
             // ...process output
        }

  • 相关阅读:
    (Tree) 101. Symmetric Tree
    (String). Word Pattern
    (Array)121. Best Time to Buy and Sell Stock
    (Array)169. Majority Element
    记录一次工作问题总结——关于游戏物体渲染顺序
    C++——STL(算法)
    观察者设计模式
    二分查找——校招题
    排序算法——归并排序
    排序算法——堆排序
  • 原文地址:https://www.cnblogs.com/watchdatalearn2012620/p/3145888.html
Copyright © 2020-2023  润新知