@CarlosP's answer與代碼逃脫路徑&參數:
- (BOOL)runProcessAsAdministrator:(NSString*)scriptPath
withArguments:(NSArray*)arguments
output:(NSString**)output
errorDescription:(NSString**)errorDescription {
//Check path.
if (![scriptPath hasPrefix:@"/"]) {
@throw [NSException exceptionWithName:
NSInvalidArgumentException reason:@"Absolute path required." userInfo:nil];
}
//Define script.
static NSAppleScript* appleScript = nil;
if (!appleScript) {
appleScript = [[NSAppleScript alloc] initWithSource:
@"on run commandWithArguments\n"
" activate\n"
" repeat with currentArgument in commandWithArguments\n"
" set contents of currentArgument to quoted form of currentArgument\n"
" end repeat\n"
" set AppleScript's text item delimiters to space\n"
" return do shell script (commandWithArguments as text) with administrator privileges\n"
"end run"];
}
//Set command.
NSAppleEventDescriptor* commandWithArguments = [NSAppleEventDescriptor listDescriptor];
[commandWithArguments insertDescriptor:
[NSAppleEventDescriptor descriptorWithString:scriptPath] atIndex:0];
//Set arguments.
for (NSString* currentArgument in arguments) {
[commandWithArguments insertDescriptor:
[NSAppleEventDescriptor descriptorWithString:currentArgument] atIndex:0];
}
//Create target & event.
ProcessSerialNumber processSerial = {0, kCurrentProcess};
NSAppleEventDescriptor* scriptTarget =
[NSAppleEventDescriptor descriptorWithDescriptorType:typeProcessSerialNumber bytes:&processSerial length:sizeof(ProcessSerialNumber)];
NSAppleEventDescriptor* scriptEvent =
[NSAppleEventDescriptor appleEventWithEventClass:kCoreEventClass
eventID:kAEOpenApplication
targetDescriptor:scriptTarget
returnID:kAutoGenerateReturnID
transactionID:kAnyTransactionID];
[scriptEvent setParamDescriptor:commandWithArguments forKeyword:keyDirectObject];
//Run script.
NSDictionary* errorInfo = [NSDictionary dictionary];
NSAppleEventDescriptor* eventResult = [appleScript executeAppleEvent:scriptEvent error:&errorInfo];
//Success?
if (!eventResult) {
if (errorDescription)
*errorDescription = [errorInfo objectForKey:NSAppleScriptErrorMessage];
return NO;
} else {
if (output)
*output = [eventResult stringValue];
return YES;
}
}
更新
在優山美地,do shell script
只是調用的AuthorizationExecuteWithPrivileges
一個version嵌入StandardAdditions.osax
。
可以想象,的with administrator privileges
選項將在AuthorizationExecuteWithPrivileges
時消失。
個人而言,我會直接繼續撥打AuthorizationExecuteWithPrivileges
。
do shell script
自動具有reaping the process的優勢。這需要一些extra work與AuthorizationExecuteWithPrivileges
。
我仍然在尋找是否有選項不需要Apple的授權/購買許可證,但是要感謝關於如何在「最壞情況」情況下優雅地失敗的示例!有趣的是看看那裏是如何處理的! – Tiago
@loco你可能已經看到了這個,但[你可以使用Applescript](https://stackoverflow.com/questions/6841937/authorizationexecutewithprivileges-is-deprecated)。如果你走這條路線,確保你使用'quoted form'來[清理可執行文件路徑和參數](https://developer.apple.com/library/mac/technotes/tn2065/_index.html#//apple_ref/DOC/UID/DTS10003093-CH1-SECTION3)。 – 2015-07-23 02:19:32