objective-c - 在 cocoa 应用程序中使用 NSTask 执行命令时 sudo 身份验证 session

标签 objective-c cocoa sudo

我有一个需要使用 sudo 执行命令的应用程序。我如何请求密码,如果成功,则使用 NSTask 运行 sudo 命令。

最佳答案

如果您正在寻找更轻量级的解决方案,还有另一种方法。我写了这个通用实现,它应该可以实现你想要的:

- (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
    }

user950473 致敬.

关于objective-c - 在 cocoa 应用程序中使用 NSTask 执行命令时 sudo 身份验证 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6632295/

相关文章:

objective-c - 在 Objective-C 上设置淡入淡出效果

java - 无法运行 solr(无法打开日志文件)

linux - shell 脚本中的 su 和 sudo

objective-c - 无法识别的选择器发送到合成属性上的实例

ios - 更智能的自动资本化

ios - 后台警报(ios 7)

iPhone开发-调用外部JSON API(Apple会拒绝吗?)

swift - 在运行时更改调度程序的时间间隔

iphone - 显示 Plist 词典中的随机单词 - 内存泄漏?

linux - 须藤-i : why does this give a root shell?