开发者

Cocoa shell command permission

开发者 https://www.devze.com 2022-12-11 00:05 出处:网络
I\'m developing my first Mac App have some issues with shell commands... I\'m trying to find out how to get the permission windows that the user can enter his password. I want to copy a picture in a s

I'm developing my first Mac App have some issues with shell commands... I'm trying to find out how to get the permission windows that the user can enter his password. I want to copy a picture in a system folder, and change the name of another picture too. I try to change the Login window background.

Command 1: "sudo mv DefaultDesktop.jpg DefaultDesktop_copy.jpg"

Command 2: "sudo cp /path/of/image.jpg DefaultDesktop.jpg"

With the terminal, it is very easy. But with an interface, i would like this prompt asking for the password.

Here is my code for the first command:

- (void)copyDefaultBackground:(id)sender {
    NSTask *task;
    task = [[NSTask alloc] init];
    [task setLaunchPath: @"/usr/bin/sudo"];

    NSArray *arguments;
    arguments = [NSArray arrayWithObjects:@"mv"
                            @"/System/Library/CoreServices/DefaultDesktop.jpg",
                            @"/System/Library/CoreServices/DefaultDesktop_copy.jpg", 
                            nil];
    [task setArguments: arguments];

    NSPipe *pipe;
  开发者_运维技巧  pipe = [NSPipe pipe];
    [task setStandardOutput: pipe];

    NSFileHandle *file;
    file = [pipe fileHandleForReading];

    [task launch];

    NSData *data;
    data = [file readDataToEndOfFile];

    NSString *string;
    string = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog (@"Script returned:\n%@", string);
}

Update:

I found that NSFileManager is an object that allow to manage file on the disk. Isn't it better than using a NSTask with a shell command?

Thank you.


You will need to use Authorization Services to authorize the move:

Introduction to Authorization Services Programming Guide

For the file move itself, why not use NSFileManager? Authorization aside, both your steps (make a backup, then move the new file into place) can be done with a single line of code each with NSFileManager.


What you want is STPrivilegedTask, which is an NSTask-like class which abstracts Authorization Services.

Get rid of sudo and execute the command using STPrivilegedTask -- the user will be prompted for an admin password, and your command will be executed with admin privileges.

0

精彩评论

暂无评论...
验证码 换一张
取 消