2011-07-09 14 views
3

sudoでコマンドを実行する必要があるアプリケーションがあります。どのようにパスワードを尋ねることができ、成功すれば、NSTaskを使ってsudoコマンドを実行します。sudo authココアアプリケーションでNSTaskを使ってコマンドを実行中のセッション

+0

[NSTask-objective-cを使用して許可を与える方法](http://stackoverflow.com/questions/3541654/how-to-give-permission-using-nstask-objective-c) –

+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; 
    } 
} 

使用例:user950473

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 
    } 

Hatの先端私はあなたが望むものを達成する必要があり、この一般的な実装を書きました。

+0

このコードのアプリはApp Storeで使用できますか? – sabes

+0

@sables私は試していないので、私はそれについてコメントできませんでした。 –

関連する問題