2012-05-08 18 views
4

私はNSTaskで次のコマンドを実行しようとしています:NSTask実行スクリプト

NSTask *server = [NSTask new]; 
[server setLaunchPath:@"/bin/launchctl"]; 
[server setArguments:[NSArray arrayWithObjects:@"load",@"com.devdaily.crontabtest.plist",nil]]; 
[server setCurrentDirectoryPath:@"/Users/admin/Library/LaunchAgents/"]; 

NSPipe *outputPipe = [NSPipe pipe]; 
[server setStandardInput:[NSPipe pipe]]; 
[server setStandardOutput:outputPipe]; 

[server launch]; 
[server waitUntilExit]; // Alternatively, make it asynchronous. 
[server release]; 

しかし、それが原因でsudoコマンドでは動作しません:

以下
$sudo launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist 

は、私が使用するコードです。 。これをどうすれば解決できますか?

+0

コンソール以外の環境で 'sudo'を使うのは、パスワードを簡単に入力する方法がないのであまり役に立ちません(標準入力パイプを使うことができますが、OS Xの組み込みエスカレーションユーティリティを使う方がはるかに優れています)。第二に、sudoがパスをロードしていないので、 'sh'によってロードされていないと思います。 –

答えて

1

残念ながら、にできません。パスワードを入力する方法がないためです。

ただし、代わりにNSTaskNSAppleScriptを使用して、bashコマンドを実行することができます。 のようなAppleScriptを書く:

do shell script[your command]with administrator privileges

をあなたが管理者パスワードを要求されます。

例:

NSDictionary *error = [NSDictionary new]; 
NSString *script = @"do shell script \"launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist\" with administrator privileges"; 
NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; 
if ([appleScript executeAndReturnError:&error]) { 
    NSLog(@"success!"); 
} else { 
    NSLog(@"failure!"); 
} 
関連する問題