We've all been there. You have a bunch of servers that all need to have a specific job to be run on a scheduled basis. Of course, there are specialized tools that can automate this process like Ansible, Puppet, and Chef, but sometimes, you just want a quick and dirty solution.

Well, you can always use the plain old Bash shell to get the task done. Let's first see how a cron job can be created manually:

  1. Run crontab -e to open the cron page using the default editor (vim or nano).
  2. Add the cron job like: 0 0 * * * ntpdate myntp.mydomain.com to update the server time using the NTP protocol every day at midnight.
  3. Save the file.

That might be just OK for a couple of servers. But, if you have dozens, this might quickly get time wasting.

Fortunately, cron has another way of accepting jobs: just using the cron command, followed by a text file containing the cron jobs that you want cron to handle. For example, if I have a file called jobs.txt that contains cron jobs, I can add it to cron as follows: cron jobs.txt

Yet, there is one caveat here: when using cron this way, you are replacing all your cron jobs with the ones in the file.

The solution for this is simple, just dump all the contents of the current crontab jobs to a file, add whatever jobs to that file, then use cron with that file. So, the previous example can be re-written as follows:

  1. crontab -l > jobs.txt #Dump the existing cron jobs to a file
  2. echo "0 0 * * * ntpdate myntp.mydomain.com" >> jobs.txt # Add a new job to the file
  3. cron jobs.txt # Use cron to configure crontab with the jobs in the file That's more than enough if you just want to add a new job to crontab. But, what if you want to change the job that already exists? Simply, you can change step 1 to be as follows: crontab -l | grep -v ntpdate > jobs.txt

The difference here is that we instructed Bash to output all the content of the crontab file excluding the job that contained ntpdate. We used grep with the -v option, which means grab everything except what comes after -v.

Back to our case, now you can create a script (script.sh) that will automate this cronjob creation. It may look as follows:

crontab -l > /tmp/jobs.txtecho "0 0 * * * ntpdate myntp.mydomain.com" >> /tmp/jobs.txt
cron /tmp/jobs.txt

Now, you can use the SSH command from your local machine (that's running Linux, MAC, or Windows with CYGWin), and issue a command like the following:

ssh root@myserver bash < script.sh

I hope you liked this post. Please drop me a comment if you have any questions.