Run crontab non-interactively from script

2

I would like to schedule some tasks on remote servers by script but am having an issue with crontab expecting to be run interactively the first time. As far as I understand crontab needs to be initialized by first running crontab -e. Which causes it to prompt which editor to use and launch that editor.

I need initialize crontab and schedule a task on too many servers to log into each individually. Is there a way I can avoid the interactive part or script it?

The servers and my client are running Ubuntu 13.04.

Nash0

Posted 2013-08-12T02:09:49.187

Reputation: 211

Answers

3

From StackOverflow: Linux - How do I create a crontab thru a script

Cron jobs usually are stored in a per-user file under /var/spool/cron

The simplest thing for you to do is probably just create a text file with the job configured, then copy it to the cron spool folder and make sure it has the right permissions.

Brian

Posted 2013-08-12T02:09:49.187

Reputation: 8 439

1

I am fairly new to linux shell scripting and I found the answers in the SO post Brian mentioned to be incomplete. They were a great help and had most of the information I needed but I ran into a couple issues wit permissions and executing commands over ssh. My final solution is:

cd ~/
echo "" > x
sudo cp ~/x /var/spool/cron/crontabs/myuser
sudo chown myuser:crontab /var/spool/cron/crontabs/myuser
echo "*/20 * * * * /path/to/myscript" > c
cat ~/c | crontab -

First I create an empty crontab file, then correct the permissions to what crontab needs, then put the cron command in a file and finally tell crontab to schedule the script.

Adding the cron command to a file instead of using echo was necessary because I was having issues with quoting over ssh.

Nash0

Posted 2013-08-12T02:09:49.187

Reputation: 211

0

You can edit the entries of the crontab without using the -e option as follows.

#write out current crontab
crontab -l > mycron
#echo new cron into cron file
echo "<new crontab entry>" >> mycron
#install new cron file
crontab mycron
rm mycron

This works really well for creating/editing (use sed) crontab entries via scripts.

Source: StackOverflow

Sai Kiriti Badam

Posted 2013-08-12T02:09:49.187

Reputation: 111

-1

For complex or large scale job scheduling, cron starts to become difficult to manage. At work I use an enterprise (and expensive) scheduler which makes managing our 300+ jobs a breeze, but there are also very decent freely available solutions out there.

I suggest moving away from cron, especially when you have too many servers to log into individually. Managing them can be a real pain. Try googling "free job scheduler Linux" or have a look at http://juiceboxjobs.com which I use with my 3D rendering farm at home (running Ubuntu 12.04).

Lee Beng

Posted 2013-08-12T02:09:49.187

Reputation: 1