Making Mac OSX launchctl launch a process as root on startup

Keith John Hutchison picture Keith John Hutchison · Jun 13, 2013 · Viewed 19k times · Source

My question is how to make a MacOSX daemon process using launchd start with root privileges automatically after a reboot?

I'm writing an application for in house use that blocks access to web sites. It is written in python and modifies the /ect/hosts file to disable or enable listed urls. The main application is in django and I created a python twisted daemon that does the actual modification of the /etc/hosts file as root access privileges are required.

I have created a plist file which works with one minor issue. After rebooting the daemon process has my normal logon privileges instead of root privileges.

A workaround is to stop the process with my normal privileges then startup the process with sudo.

launchctl unload /Library/LaunchAgents/com.balanceinfosystems.socialshields.twisted.plist 
sudo launchctl load /Library/LaunchAgents/com.balanceinfosystems.socialshields.twisted.plist 

The plist file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC -//Apple Computer//DTD PLIST 1.0//EN http://www.apple.com/DTDs/PropertyList-1.0.dtd >
<plist version="1.0">
  <dict>
    <key>Label</key>
    <string>com.balanceinfosystems.socialshields.twisted</string>
    <key>Program</key>
    <string>/source/social_shields/social_shields_twisted.py</string>
    <key>KeepAlive</key>
    <true/>
  </dict>
</plist>

Answer

Rob Napier picture Rob Napier · Jun 13, 2013

You've put this in the wrong directory. LaunchAgents are processes run per-user. System processes go in /Library/LaunchDaemons. They are run as root. If you want this to run at startup, I recommend making that explicit with:

<key>RunAtLoad</key>
<true/>