Search code examples
macosterminalapplescriptrootsudo

Apple Script to run an application as root


I am trying to use an Apple Script to run an application as root without asking for password all the time. I used this Apple Script code:

do shell script "/Applications/MyApp.app" user name "<username>" password "<password>" with administrator privileges

This works, but it makes the Apple Script to keep on running without closing. Not only that, the application that runs using this Apple Script gets stuck and could not be closed unless macOS is restarted. Even Force Quit is not working.

I also tried this method,

I created another script that can allow the app to run as root without asking for password. Here is that code,

set sudoersFilePath to "/etc/sudoers"
set newEntry to "username ALL=(ALL) NOPASSWD: /Applications/MyApp.app"

do shell script "echo " & quoted form of newEntry & " | sudo tee -a " & sudoersFilePath with administrator privileges

The above script adds a line in the sudoers file. You can access this file from Terminal using this command,

sudo visudo

This will list all the files in the list that do not require password all the time. In the sudoers file, it has added the line to give full root access to the macOS user. This file contains the required application, but it is not running as root.

So, how to run the application as root without asking for password using Apple Script or any other method?


This script, as I mentioned above, works,

do shell script "/Applications/MyApp.app" user name "<username>" password "<password>" with administrator privileges

But, it is making Apple Script and the application to continually run. Even Force Quit is not working. Is there a way to fix this from continually run and be able to quit it?


Solution

  • Thanks to VonC and Vincent for the information provided. I found a solution. This Apple Script worked:

    do shell script "/Applications/MyApp.app/Contents/MacOS/myapp > /dev/null 2>&1 &" user name "username" password "password" with administrator privileges
    quit
    

    It would seem that some macOS application are restricted way too much that prevents it from running as root without asking for password. But, it worked on other applications.