2

I want to execute a command from objective C (Cocoa framework). The command I am trying is as below. I tried with NSTask but it says "launch path not accessible" when I execute it.

sudo ifconfig en0 down 

My code is:

- (void)testme {
NSTask *task;
task = [[NSTask alloc] init];
[task setLaunchPath: @"sudo ifconfig en0 down"];

NSArray *arguments;
arguments = [NSArray arrayWithObjects: @"foo", @"bar.txt", 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];
NSLog (@"command returned:\n%@", string);

[string release];
[task release];

}

2 Answers 2

5

sudo ifconfig en0 down is not a sensible launch path. The correct launch path for this command would be /usr/sbin/sudo.

Once that is done, you still need to pass the correct arguments to setArguments:. foo and bar.txt look like example code that you copied without reading.

MORE IMPORTANTLY, THOUGH, running sudo from NSTask will not work. You will need to use Authorization Services to launch a privileged command.

Sign up to request clarification or add additional context in comments.

2 Comments

Ok. I could run it via " char *command = "sudo ifconfig en0 down"; system(command);" but it asks me system admin credentials. Any idea how to get rid of it?
You can't. Use Authorization Services.
1

You need to specify the full executable path and you should specify the arguments as the arguments, not along with the launch path. NSTask ain't a shell, it internally uses syscalls (execv(), I guess) to invoke the command.

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

NSArray *arguments = @[@"ifconfig", @"en0", @"down"];
[task setArguments:arguments];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.