2012-05-08 90 views
4

我試圖運行與NSTask以下命令:NSTask運行腳本

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

下面是我的代碼使用方法:

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命令的工作。我怎樣才能解決這個問題?

+0

在非控制檯環境中使用'sudo'並不是很有用,因爲沒有簡單的方法輸入密碼(是的,您可以使用標準輸入管道,但使用OS X的內置升級實用程序要好得多)。其次,我猜測sudo沒有被'sh'加載,因爲它沒有加載路徑。 –

回答

1

不幸的是,你不能。因爲沒有辦法輸入密碼。 寫一個AppleScript喜歡:

然而,你仍可以通過使用NSAppleScript代替NSTask運行bash命令

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!"); 
}