0

I am trying to modify the crontab of the root user through a script of python (main.py).

This script will open the crontab for root user and will modify it inserting a new command to call single.py with a parameter. The command used is not the problem as I have run it from the command line and it works. When I run the main.py script I can see the new entry when I run the crontab -l command. Everything looks correct but it does not work when is the time (nothing has been executed).

Doing some checks, if I execute the crontab -e command and I insert the command manually; when I save and close it; it shows: **crontab: installing new crontab** and then it works.

main.py:

fname = "/var/spool/cron/crontabs/root"
f = open(fname,"w+")

f.write("24 19 16 01 * python /home/pi/single.py 2087111972\n")

f.close() # save and close cron file

BTW: As this script has to be recursive (it will call itself for rescheduling its execution by modifying the crontab), is there anyway to apply the changes on crontab through the script?

P00LR0CK
  • 19
  • 10
  • Does this answer your question? [Restarting cron after changing crontab file?](https://stackoverflow.com/questions/10193788/restarting-cron-after-changing-crontab-file) – Marcin Orlowski Jan 16 '20 at 18:43
  • 1
    The `crontab` command sends a message to `cron` telling it to pick up the changes. If you modify the file directly, it never realizes that it changed. – Barmar Jan 16 '20 at 18:44
  • 1
    Your code completely replaces the crontab. You should use `a` mode when opening to add to it. – Barmar Jan 16 '20 at 18:45
  • 1
    Also, you need to write a newline at the end. – Barmar Jan 16 '20 at 18:46
  • Also, you should only append that line once, if it isn't already in the crontab file. – smci Jan 16 '20 at 18:47
  • If this is root's crontab, it doesn't need to use `sudo`. – Barmar Jan 16 '20 at 18:47
  • Thank you for the help! As this script has to be recursive (it will call itself for rescheduling its execution by modifying the crontab), is there anyway to apply the changes on crontab through the script? – P00LR0CK Jan 16 '20 at 18:47
  • This isn't specifically a Python issue, it's generic to whenever you try to edit crontab without using `crontab -e` [What is the risk when editing crontab file without the "crontab -e" command?](https://stackoverflow.com/questions/24022154/what-is-the-risk-when-editing-crontab-file-without-the-crontab-e-command) – smci Jan 16 '20 at 18:49
  • 1
    [python-crontab library](https://pypi.org/project/python-crontab/) – Barmar Jan 16 '20 at 18:51
  • Separately, *"this script has to be recursive (it will call itself for rescheduling its execution by modifying the crontab)"* sounds like a bad idea. Why can't you have the scheduled dayofmonth, monthofyear be `* *` instead of 1/16? Then let the script figure out what to do based on the particular date? – smci Jan 16 '20 at 18:55

0 Answers0