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 ~/Library/LaunchAgents/com.sudoexample.plist
<?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">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.sudoexample</string>
<key>ProgramArguments</key>
<array>
<string>sudo</string>
<string>touch</string>
<string>/tmp/sudoexample</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>StandardOutPath</key>
<string>/tmp/sudoexample.log</string>
<key>StandardErrorPath</key>
<string>/tmp/sudoexample.log</string>
</dict>
</plist>
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 /tmp/sudoexample.log
.
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/
sudoexample.log
$ 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
total 0
-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 /tmp/sudoexample
.
Thanks to klanomath's answer for providing the foundation for this one.