objective-cxcodemacososx-leopard

Write file to etc directory in mac os x


I am trying to write file into /etc folder on Mac OS X.

[[textView string] writeToFile:@"/etc/info.txt" atomically:YES encoding:NSUnicodeStringEncoding error:&error];

It throws error that I don't have permission to write there ( naturally ), but I don't understand how to get permission to be able to write into the System folders.

Also can somebody provide simple example?

Please help. Thank you.


Solution

  • Okay, after researching quite a bit I believe I found a more/less simple method. First check out the link: Cocoa - Gaining Root Access for NSFileManager

    They suggest using already made class "BLAuthentication" - which takes care of lots of authentication coding for you. Google it to download, add to the project and use in your code. Here is a example of how simple that is:

    id blTmp = [BLAuthentication sharedInstance];
    
    NSString *myCommand = [[NSString alloc] initWithString:@"/bin/cp"];
    
    NSArray *para = [[NSArray alloc] initWithObjects:fileName, @"/etc/", nil];
    
    [blTmp authenticate:myCommand];
    
    if([blTmp isAuthenticated:myCommand] == true) {
        NSLog(@"Authenticated");
        [blTmp executeCommandSynced:myCommand withArgs:para];
    
    } else { NSLog(@"Not Authenticated"); }
    
    [fileName release];
    [myCommand release];
    [para release];
    

    Naturally above approach doesn't exactly answers my own question, since with above example you don't directly write to "/etc". Instead first I have to write file to "/tmp" (or other directory of your choice) and then using "cp" command in unix, copy it over to "/etc" (using "BLAuthentication" for authentication).

    This is the simplest to do it, that I managed to find.

    *Note: This method might not work in Lion (Mac os 10.7) since "BLAuthentication" uses deprecated function "AuthorizationExecuteWithPrivileges". Also I would suggest watching WWDC 2011 where they talk about security and proper ways of accomplishing the task. However if you need to prototype and/or play around, "BLAuthentication" should do the trick.