15

Do I properly understand that it is not possible to run /etc/cron.daily/my from arbitrary user, it will be run only from root according to /etc/crontab?

Can I drop root privilege to specific user in my cron scrip instead?

It is better to place cron job into /etc/cron.d? Like:

$ cat /etc/cron.d/my
5 0 * * *  user  test -x /usr/bin/my && /usr/bin/my -cfg /etc/my.cfg

1 Answer 1

21

You are right, the jobs in /etc/cron.daily (and weekly/monthly, etc.) are always executed as user root but you can simply swith the user from within the script and call that very script again as that other user, including all supplied arguments (although there won't be any in a cron.daily job):

File /etc/cron.daily/my:

#!/bin/sh

# If started as root, then re-start as user "gavenkoa":
if [ "$(id -u)" -eq 0 ]; then
    exec sudo -H -u gavenkoa $0 "$@"
    echo "This is never reached.";
fi

echo "This runs as user $(id -un)";
# prints "gavenkoa"

exit 0;

When the script is started as user root it will detect so and re-execute itself via sudo -H -u gavenkoa, that is: as user gavenkoa. This requires no special entries in /etc/sudoers because root is always allowed to switch to any user.

The exec replaces the current process with the new sudo … call and never returns. That's why you don't need an else clause.

2
  • 1
    As I understand sudo isn't POSIX utils. Is su available in all UNIXes?
    – gavenkoa
    Dec 30, 2018 at 13:32
  • 2
    @gavenkoa We are talking about Ubuntu, aren't we? There sudo is always installed. But if you prefer su instead, you can of course replace the sudo call with su but be aware that it's more complicated to pass the arguments "$@" to su, see Pass arguments to a command run by another user over on U&L.
    – PerlDuck
    Dec 30, 2018 at 14:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.