Running cron jobs using the www-data system account
Published on 22nd December 2018 Estimated Reading Time: 2 minutesWhen you set up your own web server or use a private server (virtual or physical), you will find that web servers run using the www-data
account. That means that website files need to be accessible to that system account if not owned by it. The latter is mandatory if you want WordPress to be able to update itself with needing FTP details.
It also means that you probably need scheduled jobs to be executed using the privileges possessed by the www-data
account. For instance, I use WP-CLI to automate spam removal and updates to plugins, themes and WordPress itself. Spam removal can be done without the www-data
account, but the updates need file access and cannot be completed without this. Therefore, I got interested in setting up cron jobs to run under that account and the following command helps to address this:
sudo -u www-data crontab -e
For that to work, your own account needs to be listed in /etc/sudoers
or be assigned to the sudo group in /etc/group. If it is either of those, then entering your own password will open the cron
file for www-data
, and it can be edited as for any other account. Closing and saving the session will update cron
with the new job details.
In fact, the same approach can be taken for a variety of commands where files only can be accessed using www-data
. This includes copying, pasting and deleting files as well as executing WP-CLI commands. The latter issues a striking message if you run a command using the root account, a pervasive temptation given what it allows. Any alternative to the latter has to be better from a security standpoint.