14

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

2
  • Do you mean you put the script in the directories mentioned or the launchd plist?
    – mmmmmm
    Jun 5, 2013 at 10:25
  • Ah sorry, I'm talking about a plist which runs the script. Jun 5, 2013 at 10:46

2 Answers 2

13

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

4
  • 1
    Unlike LaunchAgents, LaunchDeamon cannot use UserName. They run without loggin in a user. May 4, 2015 at 20:40
  • 1
    @Julian where is this documented - and I think this used to work so what OS X chnage this
    – mmmmmm
    May 5, 2015 at 9:37
  • 1
    @JulianF.Weinert - just run it as root. sudo launchctl ..... for your UserName to be used by launchtl. This is docummented in the man page UserName <string> This optional key specifies the user to run the job as. This key is only applicable when launchd is running as root.
    – Mick
    Feb 1, 2018 at 22:23
  • 1
    On macOS launchd is always run as root. The man page only covers this for non-macOS systems.
    – max
    Apr 13, 2018 at 12:54
3

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .