What is the proper way to run something like $sudo touch folder_name
or $sudo rm
from within Objective-C/Cocoa? I'm changing and moving around a few files and need elevated privileges. Any code sample would be greatly appreciated. Thanks.
views:
341answers:
2
+5
A:
One way to do it is AuthorizationExecuteWithPrivileges()
, but that's discouraged for the normal course of things. Mainly it's for installers, I gather.
Something like:
AuthorizationRef auth = NULL;
OSStatus err = AuthorizationCreate(NULL, kAuthorizationEmptyEnvironment, kAuthorizationFlagInteractionAllowed, &auth);
err = AuthorizationExecuteWithPrivileges(auth, command, kAuthorizationFlagDefaults, args, NULL);
And you add appropriate checking of err
...
See the Authorization documentation.
jeffamaphone
2010-01-23 00:58:50
thanks this is exactly what I was looking for.
Jeff
2010-01-23 05:14:14
+1
A:
There are several ways to do this. Which one you choose depends on what you want to do. The simplest and unsafest way is to simple set the s-bit on an extra helper tool that you call from your code and does what needs admin rights. Take a look at the BetterAuthorizationSample for the most fancy and complicated way of executing privileged code.
The Authorization Services Programming Guide gives you all you need.
Hutaffe
2010-01-23 01:42:37
“The simplest and unsafest way is to simple set the s-bit on an extra helper tool that you call from your code and does what needs admin rights.” That's actually the way Apple recommends. You're supposed to use `AuthorizationExecuteWithPrivileges` only to confer the setuid bit on the helper tool. The idea is to confine root powers to only the code that needs powers (the task-specific helper tool), so that code that doesn't need powers (your app) doesn't have them. It's the Principle of Least Privilege.
Peter Hosey
2010-01-23 01:56:43