问题
Ok, I am using NSTask to run a shell script that needs to be run with administrator privileges. I am using some code from this question: NSTask and AuthorizationCreate. Here is what I currently have:
//Authorization Create
AuthorizationRef myAuthorizationRef;
OSStatus myStatus;
myStatus = AuthorizationCreate (NULL, kAuthorizationEmptyEnvironment,
kAuthorizationFlagExtendRights | kAuthorizationFlagInteractionAllowed , &myAuthorizationRef);
AuthorizationItem myItems[1];
myItems[0].name = "com.myOrganization.myProduct.myRight1";
myItems[0].valueLength = 0;
myItems[0].value = NULL;
myItems[0].flags = 0;
AuthorizationRights myRights;
myRights.count = sizeof (myItems) / sizeof (myItems[0]);
myRights.items = myItems;
AuthorizationFlags myFlags;
myFlags = kAuthorizationFlagDefaults |
kAuthorizationFlagInteractionAllowed |
kAuthorizationFlagExtendRights;
myStatus = AuthorizationCopyRights (myAuthorizationRef, &myRights,
kAuthorizationEmptyEnvironment, myFlags, NULL);
if (myStatus==errAuthorizationSuccess)
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"kandorBackup" ofType:@"sh"];
NSPipe *outputPipe = [NSPipe pipe];
readHandle = [outputPipe fileHandleForReading];
inData = nil;
returnValue = nil;
NSTask *task = [[NSTask alloc] init];
[task setLaunchPath:path];
[task setArguments:[NSArray arrayWithObjects:login, selectedDrive, rsyncFinalFlags, nil]];
[task setStandardOutput:outputPipe];
[readHandle waitForDataInBackgroundAndNotify];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(recievedData:)
name:NSFileHandleDataAvailableNotification
object:nil];
[task launch];
}
myStatus = AuthorizationFree (myAuthorizationRef,
kAuthorizationFlagDestroyRights);
When this executes, I am prompted for an administrator username and password, but then the task runs like it normally would, without elevated privileges. What am I missing to make NSTask actually use the authorization?
回答1:
Here you are just getting an AuthorizationRef and doing nothing with it, just getting the authorization doesn't make your executable run privileged. You can use the ref to launch an executable you embedded in your application using SMJobSubmit and within that executable, you can use NSTask with elevated permissions. Here is some example code explaining how this works: http://www.stairways.com/blog/2012-08-06-smjobsubmit
来源:https://stackoverflow.com/questions/25086160/using-authorization-services-with-nstask