可可中有多个sudo命令

时间:2011-03-16 13:56:07

标签: objective-c cocoa

经过一番阅读后,我终于找到了如何通过cocoa执行sudo命令。但是当我尝试执行多个命令时,它只执行第一个命令。我的代码:

AuthorizationRef authorizationRef;
OSStatus status;

status = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment,
                             kAuthorizationFlagDefaults, &authorizationRef);

/* Step one: Rename current trash icon files */
// Rename trashempty icon
NSLog(@"Renaming trashempty icon");
char *trashempty_tool = "/bin/mv";
char *trashempty_args[] = {"/System/Library/CoreServices/Dock.app/Contents/Resources/trashempty.png","/System/Library/CoreServices/Dock.app/Contents/Resources/trashempty_backup.png"};

status = AuthorizationExecuteWithPrivileges(authorizationRef, trashempty_tool,
                                            kAuthorizationFlagDefaults, trashempty_args, NULL);

NSLog(@"Authorization Result Code: %d", status);
// Check for status TODO

NSLog(@"Renaming trashfull icon");
char *trashfull_tool = "/bin/mv";
char *trashfull_args[] = {"/System/Library/CoreServices/Dock.app/Contents/Resources/trashfull.png","/System/Library/CoreServices/Dock.app/Contents/Resources/trashfull_backup.png"};

status = AuthorizationExecuteWithPrivileges(authorizationRef, trashfull_tool,
                                            kAuthorizationFlagDefaults, trashfull_args, NULL);

NSLog(@"Authorization Result Code: %d", status);
你能帮帮我吗?

2 个答案:

答案 0 :(得分:0)

用苹果脚本:

NSAppleScript * script = [[[NSAppleScript alloc] initWithSource:@“do shell scritp \”echo Larcus94 \“”] autorelease];     NSDictionary * errorDict;     [script executeAndReturnError:& errorDict];

使用nstask(更好的方式):

NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"/bin/bash"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"-l", @"-a", @"-t", nil];
[task setArguments: arguments];

NSPipe *pipe;
pipe = [NSPipe pipe];
[task setStandardOutput: pipe];

NSFileHandle *file;
file = [pipe fileHandleForReading];

[task launch];

NSData *data;
data = [file readDataToEndOfFile];

NSString *string;
string = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];

答案 1 :(得分:0)

建议您创建放置在主捆绑资源中的帮助应用程序

即您将Mv代码放在帮助应用程序中, 并使用主应用程序中的授权来运行它。

这样做会为帮助应用程序提供使用auth运行的权限。 编写MV的代码会更容易。 如果您想使用NSTask在帮助应用程序中执行MV作业,则可以。

你得到了帮助应用程序的路径,并将其转换为arg,就像这样。

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString * helpPath  =[[bundle resourcePath] stringByAppendingString:@"/HelperApp" ];

const char *helperPath;
helperPath  = [helpPath cStringUsingEncoding: NSUTF8StringEncoding];

并在AuthorizationExecuteWithPrivileges

中调用helperPath

Apple有关于如何在文档中进行此操作的示例。