How can I execute sudo commands as a cron job?
Solution 1:
Cron is not in any way deprecated, but LaunchD has more versatility and is used, and actively maintained/supported by Apple. Their best practices guide is here
LaunchDaemon jobs(versus LaunchAgents, which take on a users id) run in root's context without needing to enable the root user. All that is required is a properly formed XML file(you can just copy-paste pre-existing ones in /Library/LaunchDaemons, substituting your script for the ProgramArguments with the applicable schedule keys) with the proper ownership/permissions. An older writeup can be found here: afp548's launchd-in-depth article
Solution 2:
It's a security risk, but you can enable the root user and run the command in root's cron. Alternatively, have you tried using sudo -s
to get a "root shell" and making root's cron that way. Depending on your OS level, you might not need to have root enabled as a user for it's cron to run.
If you want to do it without enabling the root user (which is not really necessary in this case), you may (as any administrative user) enter sudo crontab -u root -e
to edit root's crontab directly.