IMac – Launchd – Run as if you’re logged in as a user using sudo

imaclaunchdmacmacos

Is there a way to do this?

Basically I'm trying to run a script that needs to launch a program.

Putting the script in /Library/LaunchDaemons works fine, but everything gets run as if its the root user. This doesn't work because it needs to run as if its a real user, but using the sudo command.

So I moved the script to ~/Library/LaunchDaemons but now it won't launch the program, presumably because its getting run as the user and not with sudo permissions.

So I'm stuck. Logging in as the user and going to a terminal and running:

sudo my_command_which_launches_a_program

Works absolutely fine, and exactly how its meant to work. So I want to basically emulate that, but in a Launchd script, if possible.

Thanks

Best Answer

You put the plist into /Library/LaunchDaemons but edit it to say which user the script will run as

The key you need to add is UserName. For example I run a newserver as user _news

<key>UserName</key>
<string>_news</string>

Documented in Apple's launchd man page