简体   繁体   English

在Cocoa和Objective-C中使用sudo命令?

[英]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? 在Objective-C / Cocoa中运行类似$sudo touch folder_name$sudo rm的正确方法是什么? 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. 一种方法是使用AuthorizationExecuteWithPrivileges() ,但是对于正常的过程不鼓励这样做。 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 ... 并添加适当的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. 最简单和最不安全的方法是简单地在您从代码调用的额外帮助工具上设置s-bit,并执行需要管理员权限的操作。 Take a look at the BetterAuthorizationSample for the most fancy and complicated way of executing privileged code. 查看BetterAuthorizationSample ,了解执行特权代码的最复杂和最复杂的方法。

The Authorization Services Programming Guide gives you all you need. 授权服务编程指南为您提供所需的一切。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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