Running NSTask script

I am trying to run the following command in NSTask:

$sudo launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist 

The following is the code I'm using:

 NSTask *server = [NSTask new]; [server setLaunchPath:@"/bin/launchctl"]; [server setArguments:[NSArray arrayWithObjects:@"load",@"com.devdaily.crontabtest.plist",nil]]; [server setCurrentDirectoryPath:@"/Users/admin/Library/LaunchAgents/"]; NSPipe *outputPipe = [NSPipe pipe]; [server setStandardInput:[NSPipe pipe]]; [server setStandardOutput:outputPipe]; [server launch]; [server waitUntilExit]; // Alternatively, make it asynchronous. [server release]; 

However, this does not work due to the sudo . How can i fix this?

+4
source share
2 answers

Sorry, you can’t. Because no password is entered.

However, you can still run the bash command using NSAppleScript instead of NSTask : Write an application like:

do shell script [your command] with administrator privileges

You will be prompted for an administrator password.

Example:

 NSDictionary *error = [NSDictionary new]; NSString *script = @"do shell script \"launchctl load /Users/admin/Library/LaunchAgents/com.devdaily.crontabtest.plist\" with administrator privileges"; NSAppleScript *appleScript = [[NSAppleScript new] initWithSource:script]; if ([appleScript executeAndReturnError:&error]) { NSLog(@"success!"); } else { NSLog(@"failure!"); } 
+1
source

Read the Apple Secure Encryption Guide and follow the Safe Elevation Guidelines.

In other words, do not use sudo or something like this. Use SMJobBless() to install and activate your launch agent. See also sample project SMJobBless .

0
source

Source: https://habr.com/ru/post/1411322/


All Articles