Come dare il permesso utilizzando NSTask - Objective-C [duplicato]
-
30-09-2019 - |
Domanda
Questa domanda ha già una risposta qui:
- Come utilizzare NSTask come root? 5 risposte
ho bisogno di fare fondamentalmente un "sudo", ma, devo dare quel tipo di permesso al mio codice NSTask. È possibile?
Grazie, Elia
Soluzione
Altri suggerimenti
Se siete alla ricerca di una soluzione più leggera, ho scritto questa implementazione generica che dovrebbe ottenere quello che vuoi:
- (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;
}
}
Esempio di utilizzo:
NSString * output = nil;
NSString * processErrorDescription = nil;
BOOL success = [self runProcessAsAdministrator:@"/usr/bin/id"
withArguments:[NSArray arrayWithObjects:@"-un", nil]
output:&output
errorDescription:&processErrorDescription];
if (!success) // Process failed to run
{
// ...look at errorDescription
}
else
{
// ...process output
}
E 'molto un po' hacky, ma secondo me è una soluzione soddisfacente. Credito per la scoperta di questa domanda SO .
Alcune informazioni correlate sono presentate nell'articolo " Comunicazione con uno strumento privilegiato "
Si veda anche: http://osx.hyperjeff.net/Reference/CocoaArticles? cat = 29
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow