简体   繁体   中英

Using sudo commands in Cocoa and Objective-C?

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM