Multiple sudo commands in cocoa
After some reading I f开发者_开发知识库inally found out how to do sudo commands through cocoa. But when I try to do multiple commands, it only does the first one. My code:
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);
Can you help me?
It is recommended that you create a helper app placed in your main bundle resource ,
I.e You put the Mv code in the helper app, And use the Authorization in the main app to run it.
Doing so will give the helper app the permission to run with auth. And it will be easier to write the code for the MV. You can if you want use NSTask to do the MV job in the helper app.
You get the path of the helper app and convert it for the arg like this.
NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSString * helpPath =[[bundle resourcePath] stringByAppendingString:@"/HelperApp" ];
const char *helperPath;
helperPath = [helpPath cStringUsingEncoding: NSUTF8StringEncoding];
and call helperPath in the AuthorizationExecuteWithPrivileges
Apple have example of how to go about this in the docs.
with apple script:
NSAppleScript* script = [[[NSAppleScript alloc] initWithSource:@"do shell scritp \"echo Larcus94\""] autorelease]; NSDictionary* errorDict; [script executeAndReturnError:&errorDict];
with nstask (nicer way):
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];
精彩评论