问题
I would like to the run the following command from my Cocoa project. (hides the spotlight icon)
sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search
I have found two ways how to call the command and get the following output
1) Using NSTask
NSTask *writeTask = [[NSTask alloc] init];
[writeTask setLaunchPath:@"/bin/chmod"];
[writeTask setArguments: @[@"755",@"/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search"]];
[writeTask launch];
>>chmod: Unable to change file mode on /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search: Operation not permitted
2) Pipes
NSString *command = @"sudo chmod 755/System/Library/CoreServices/Search.bundle/Contents/MacOS/Search";
fp = popen([command UTF8String], "r");
>>sudo: no tty present and no askpass program specified
I have not found a way how to run any of these in super user mode. How can I prompt the user to enter his password and eventually run this command with the required privileges?
回答1:
Write the below apple script using Apple Script Editor
and save it in a .scpt
file.
do shell script "sudo chmod 600 /System/Library/CoreServices/Search.bundle/Contents/MacOS/Search" with administrator privileges
Now add this file to your bundle.
Then to call this script from your program use the following code:
- (void) runEmbeddedScriptFile: (NSString*)fileName
{
NSString* path = [[NSBundle mainBundle] pathForResource:fileName ofType:@"scpt"];
NSURL* url = [NSURL fileURLWithPath:path];
NSDictionary* errors = [NSDictionary dictionary];
NSAppleScript* appleScript = [[NSAppleScript alloc] initWithContentsOfURL:url error:&errors];
[appleScript executeAndReturnError:nil];
[appleScript release];
}
This will prompt the password request from user.
回答2:
Prior to 10.7 you could use AuthorizationExecuteWithPrivileges()
to execute tasks with privileges. However, this has been deprecated in 10.7 and Apple recommends using the ServiceManagement
framework to perform privileged tasks.
SMJobBless demonstrates how to securely install a helper tool that performs a privileged operation and how to associate the tool with an application that invokes it.
SMJobBless uses ServiceManagement.framework that was introduced in Mac OS X v10.6 Snow Leopard.
As of Snow Leopard, this is the preferred method of managing privilege escalation on Mac OS X and should be used instead of earlier approaches such as BetterAuthorizationSample or directly calling AuthorizationExecuteWithPrivileges.
Apple's sample code
回答3:
You need to use Authorization Services to get the root privileges and then use chmod() from sys/stat.h
来源:https://stackoverflow.com/questions/20061526/sudo-chmod-command-from-cocoa