cron job causes systemd error

I hope someone can point me in the right direction here, I have a script running as root in cron but my log files indicate that it is triggering the following error.

any ideas on how I can get this corrected? Perhaps it's just a thing that needs no attention

debian systemd[4840]: Failed to open directory /home/user/.config/systemd/user/run-user-0.mount.wants: Permission denied
debian systemd[4840]: Failed to open directory /home/user/.config/systemd/user/run-user-0.mount.requires: Permission denied
debian systemd[4840]: Failed to open directory /home/user/.local/share/systemd/user/run-user-0.mount.wants: Permission denied
debian systemd[4840]: Failed to open directory /home/user/.local/share/systemd/user/run-user-0.mount.requires: Permission denied

my cronjob entry is also below;

0 */1 *. *. *. su root -c "/etc/myscript/mysript.sh" >  /dev/null 2>&1

The script, which when ran by sudo does not cause the error, only as a cronjob.


Solution 1:

First of all, if you want to run a cronjob "as root", shouldn't you just put the entry in the cronjob of the root user itself? So su and then edit the cronjob and put the entry there (without the su)

0 */1 *. *. *. /etc/myscript/mysript.sh >  /dev/null 2>&1

Other than that I would like to point out how to debug cronjobs, because most people don't know and the problem starts there. The cron environment is a limited environment that doesn't know about all system variables, etc. that your user does. So often that can cause problems.

So to debug a cronjob you would like to debug from the actual cron environment.

To do that, first put this in your crontab:

* * * * * env > ~/cronenv

This will export the environment variables of the crontab to the cronenv file in your home directory every minute. So wait one minute and then remove this statement from your crontab.

Now you can switch your user to the cron environment:

env - `cat ~/cronenv` /bin/sh

And now you can debug your cron statement and see what happens:

su root -c "/etc/myscript/mysript.sh"

I expect the same error message you already got, but now it is easier to debug and fix it. Good luck!

Oh and you can always exit the cron environment by simply typing exit.