I have an executable that needs to run every time a user logs in. It needs to run in the context of that user, but with root permissions, as if the user had run it with sudo.

I have looked through Apple's documentation as well as the website launchd.info for a way to do this, but haven't been able to find anything.

If I create a Launch Agent (in ~/Library/LaunchAgents or /Library/LaunchAgents), or a Launch Daemon with the UserName property set, it runs as the user (as desired), but I cannot do anything that requires elevated privileges.

If I create a Launch Daemon (in /Library/LaunchDaemons) it runs as root (with the desired privileges), but without any user context. If I use su <username> -c "<command>" or sudo -u <username> <command> from the Launch Daemon, I can then run a command as the user, but it runs without sudo privileges.

Is there a way to run a launch agent with sudo permissions?

  • a few suggestions: this .plist generator suggests that you can specify the username. You could try <key>UserName</key> <string>root</string> (I haven't). Alternatively, you could run as root from within the script, as suggested in various ways here: askubuntu.com/questions/425754/…
    – anon01
    Jun 27, 2017 at 19:11

1 Answer 1


I'm no guru, so I don't know if this is bad advice. I'm sure I'll get killed with negatives if it is, but here goes:

If you insert a password into a user's keychain, you can access and use it in a script.

Extract the password (stored here as 'scriptsudo' in USER's keychain):

PASS=$(security find-generic-password -l "scriptsudo" -a USER -w | tr -d '\n')

Using the password for a 'chown' command in a script:

rslt=$(echo "$PASS" | sudo -S chown -R :GR-Access /Users/XXX/folder 2>&1)

-S option for sudo tells it to get the password from sysin. The echo command makes it available to sudo. In this example, the output from the sudo command is stored in 'rslt'. This is not required, I did it so I could log the result.

The script can be run from launchd using the usual plist method.

To split 'rslt' into array see https://stackoverflow.com/a/45201229/8245469 (Wrong Answer #7)

  • 1
    Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.
    – Community Bot
    Aug 4, 2022 at 16:23

You must log in to answer this question.

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