2011-07-09 52 views
3

我有一個需要使用sudo執行命令的應用程序。如何獲得密碼,如果成功,請使用NSTask運行sudo命令。使用可可應用中的NSTask執行命令時使用sudo auth會話

+0

可能的重複[如何使用NSTask授予權限 - objective-c](http://stackoverflow.com/questions/3541654/how-to-give-permission-using-nstask-objective-c) – 2011-07-09 02:27:30

+0

這是不是該問題的重複。這個問題是關於*實際使用sudo *(儘管我同意正確的答案是「使用授權服務」)。 –

回答

3

如果你尋找更輕量級的解決方案,還有另一種方法。我寫了這個通用的實現應該實現你想要的:

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

+0

在App Store中允許使用此代碼的應用程序嗎? – sabes

+0

@sables我還沒有嘗試過,所以我不能對此發表評論。 –