Launchd - Run as if you're logged in as a user using sudo

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


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


it needs to run as if its a real user, but using the sudo command

I think this belies a false assumption you are making. When a user runs sudo foobar, then the foobar command is run by the root user.

The only things that can be different when running foobar as root (instead of the user running sudo foobar) are the shell and environment variables available such as $HOME or $PATH.

If your application requires a specific shell or environment variable, just ensure that that shell or environment variable is set by the LaunchDaemon you are creating. That will save you a lot of heartache over trying to get launchd to replicate the exact experience of a specific user running sudo foobar.

To those downvoting, this information is backed up multiple times on StackExchange here, here, and here for starters.