Cocoa - Gaining Root Access for NSFileManager

╄→尐↘猪︶ㄣ 提交于 2019-12-17 18:33:41

问题


I need to move system files with NSFileManager in my application and I don't seem to have root access. What would be the easiest way to go about gaining this privilege?

I have looked into the BetterAuthorizationSample code provided by Apple, and I don't seem how I could have the NSFileManager run its task once its been given approval by the user.


回答1:


Update: To update people still using this answer for reference, BLAuthentication makes use of an old, and highly unrecommended function called AuthorizationExecuteWithPriviledges that, while working, goes against the modern security paradigm, and is deprecated (and has been for a while). You're still allowed to use it, technically, but if you're developing for Mac OS X Lion, you're more than welcome to use the ServicesManagement framework, that allows you to run code with privileges as a helper tool.

For reference on how to create and launch a privileged helper tool, take a look at one of my questions, Writing a Privileged Helper Tool with SMJobBless().


There's no real easy way to authorize NSFileManager, so you should look into using the standard mv and cp tools run under administrator authentication with the BLAuthentication class. Unfortunately, the original author's website is down, but you can easily find copies of the class floating around on Google (I can also upload a copy for you if you wish).


With BLAuthentication, what you are trying to do goes something like this:

#define MOVE @"/bin/mv"
if (![[BLAuthentication sharedInstance] isAuthenticated:MOVE]) {
    [[BLAuthentication sharedInstance] authenticate:MOVE];
}

NSArray *arguments = [NSArray arrayWithObjects:@"location1", @"location2", nil];
[[BLAuthentication sharedInstance] executeCommand:MOVE withArgs:arguments];

The code above will prompt the user for the administrator's password and authenticate the program for the default time limit of five minutes.


WARNING
Of course, always be careful with system files! Avoid moving or manipulating them when possible, especially if your program is going to be run on someone else's computer (if anything goes wrong, you're going to be blamed)!




回答2:


If you application needs to use root privileges, use Apple's Authorization Services API.

http://developer.apple.com/library/mac/#documentation/Security/Conceptual/authorization_concepts/01introduction/introduction.html#//apple_ref/doc/uid/TP30000995-CH204-TP1



来源:https://stackoverflow.com/questions/4599447/cocoa-gaining-root-access-for-nsfilemanager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!