【发布时间】:2011-07-09 02:24:30
【问题描述】:
我有一个需要使用 sudo 执行命令的应用程序。如何要求输入密码,如果成功,则使用 NSTask 运行 sudo 命令。
【问题讨论】:
-
这不是那个问题的重复。这个问题是关于实际使用 sudo(尽管我同意正确的答案是“使用授权服务”)。
标签: objective-c cocoa sudo
我有一个需要使用 sudo 执行命令的应用程序。如何要求输入密码,如果成功,则使用 NSTask 运行 sudo 命令。
【问题讨论】:
标签: objective-c cocoa sudo
如果您正在寻找更轻量级的解决方案,还有另一种方法。我编写了这个通用实现,它应该可以实现你想要的:
- (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;
}
}
使用示例:
NSString * output = nil;
NSString * processErrorDescription = nil;
BOOL success = [self runProcessAsAdministrator:@"/usr/bin/id"
withArguments:[NSArray arrayWithObjects:@"-un", nil]
output:&output
errorDescription:&processErrorDescription
asAdministrator:YES];
if (!success) // Process failed to run
{
// ...look at errorDescription
}
else
{
// ...process output
}
向user950473 致敬。
【讨论】:
使用授权服务,卢克。 (如果您曾经看到“应用程序 XYZ 需要管理员密码才能继续”,这就是它的实现方式。它确实不在工作表下使用 sudo。)
【讨论】: