Creating a LaunchAgent that runs with sudo/root privileges can be done by simply having
sudo be the command that the LaunchAgent executes.
Create PList File
Try placing this minimal example in
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
Note: Agents should typically have user file ownership, but
root ownership seems to work just fine as well.
The above example runs
sudo touch /tmp/sudoexample and logs the output to
If you run
launchctl load ~/Library/LaunchAgents/com.sudoexample.plist at this point, it will fail because
sudo will try to prompt for a password and
launchctl doesn't have any associated
tty to serve the password prompt:
$ ls /tmp/
$ cat /tmp/sudoexample.log
sudo: no tty present and no askpass program specified
Allow Elevated Privileges
We need to grant your user permission to run
sudo touch without a password.
This can be done like so:
echo "$(whoami) ALL=(ALL) NOPASSWD: $(which touch)" | sudo tee /etc/sudoers.d/touch
When you're done, the file should look something like this:
$ sudo cat /etc/sudoers.d/touch
coryklein ALL=(ALL) NOPASSWD: /usr/bin/touch
Test It Out
$ launchctl load ~/Library/LaunchAgents/com.sudoexample.plist
$ ls -l /tmp
-rw-r--r-- 1 root wheel 0 Jun 29 14:01 sudoexample
-rw-r--r-- 1 coryklein wheel 0 Jun 29 14:01 sudoexample.log
Now you can see the LaunchAgent successfully ran by creating the root owned
Thanks to klanomath's answer for providing the foundation for this one.