Wie man die Erlaubnis geben NSTask mit - Objective-c [Duplikat]
-
30-09-2019 - |
Frage
Diese Frage bereits eine Antwort hier:
- Wie NSTask als root benutzen? 5 Antworten
Ich muß im Grunde einen „sudo“ tun, aber ich brauche diese Art von Genehmigung zu meinem NSTask Code zu geben. Ist das möglich?
Danke, Elia
Lösung
Sehen Sie hier:
- http://www.sveinbjorn.org/STPrivilegedTask
- http://www.sheepsystems.com/sourceCode/authTasksCocoa.html
HTH: -)
Andere Tipps
Wenn Sie sich für eine leichtere Lösung suchen, schrieb ich diese generische Implementierung, die erreicht werden soll, was Sie wollen:
- (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;
}
}
Anwendungsbeispiel:
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
}
Es ist sehr leicht hacky, aber IMHO ist eine befriedigende Lösung. Kredit für die Entdeckung zu dieser Frage SO .
Einige Informationen sind in dem Artikel " Kommunikation mit einem Privileged-Tool "
Siehe auch: http://osx.hyperjeff.net/Reference/CocoaArticles? cat = 29
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow