2

I want to run a crontab command every 5 mins that executes a py script. The py script inturn generates a log file with midnight rotation within /var/www/logs/.The logs dir has 777 permission.

The log file has midnight rotation and when new file is created,it creates as root owner.How to ensure the ownership stays as www-data as some other scripts also write to the same file and having root ownership causes permission issue for other scripts.

One way is to put the command in,

crontab -u www-data -e

This works fine, but i want to maintain all my cron commands under root user.

I tried doing the same with sudo, but it creates with root as owner which not what i want.

ns15
  • 121

3 Answers3

1

So you want to have

  • all your crontabs in one place under root
  • execute some python code every 5 minutes
  • execute the script with user www-data

Since su is not available for www-data as discussed in the comments one can use sudo instead if it is available on the system. From the man page it says

sudo, sudoedit — execute a command as another user

In your case this would mean you use

sudo crontab -e

to edit your crontab as user root. Inside crontab prepend sudo -u www-data python command to execute python ad user www-data.

*/5 * * * * sudo -u www-data python /my/python/log/script.py
ukos
  • 774
  • 10
  • 25
1

More a workaround but you could also let your script be running as root as it is and let the file to be created by root. And than just add in the end

 && sudo chown www-data <your Log file>

to finally transfer the ownership of the file to www-data.

(If there are more files than you probably also are interested in the -R flag for "recursive" to run chown on an entire folder and it's content)

derHugo
  • 3,376
  • 5
  • 34
  • 52
1

I want to maintain all my cron commands under root user.

To maintain all cron jobs (which can be run as various users) in one place, forget the crontab command and edit the system-wide crontab in the file /etc/crontab instead, or add your own crontab to the directory /etc/cron.d. As you expected, it will require root access.

These files look much like any other crontabs but they include the username column, so you can just specify the target user and do not have to use sudo or such things.

Keep in mind that unlike the command crontab, you are directly editing the system configuration files, so your changes won’t be checked after you exit the editor. So please edit them with enough attention.

Melebius
  • 11,750