Wednesday, July 10, 2013

Adding cronjobs using crontab in Ubuntu 12.04/Mint 13

Cronjobs are a good way to run a script every so often (hour, day, week, at reboot, etc.) Some things I use it for are:
To keep my public ip address updated and saved in my Dropbox folder,
To mount my external hard drive on my ubuntu server every time it reboots,
And to update my psmouse-alps driver which needs to be updated at reboot as well.

I'm sure someone else can find many other possible more useful applications for this.

First think you need to do is find out what privileges you need to do what you want to do. Since all i need to update my public ip is access to the internet and also my dropbox folder, I only needed my regular user privileges.

Crontab has some pretty good explanations and even gives you an example in the comment in the file. The first 5 fields (separated by spaces) are to tell it when/how often you want to run a certain command/script. Right after the first five fields you just put the command/script you want to run.
The example used in the file:

0 5 * * 1 tar -zcf /var/backups/home.tgz /home/

I found some pretty good examples to help you to understand the schedule notation that crontab uses. Wikipedia has a useful article here. Also this site was very useful. What I found was also very useful was some of the shortcuts, listed here.
They are:
@reboot
@yearly
@annually
@monthly
@weekly
@daily
@midnight
@hourly 

So on my ubuntu server, since I need root privileges to mount my external drive, I edit the crontab by executing:
sudo crontab -e
Then I choose to edit it with vim since it is my preferred text editor, and add this line to have my external hard drive mount at boot:
@reboot mount -t ntfs-3g /dev/sdb1 /media/external
And to have my ip update every day I run:
crontab -e
(as a regular user, I don't need root for this)
and have it run my script to update the ip daily:
@daily /home/user/bin/ip_script
For any interested my script is very simple(3 lines), and only needs the curl utility installed.
sudo apt-get install curl
also dropbox if you don't already have it.
then open a text editor and write

#! /bin/bash
curl ifconfig.me >> public_ip
mv public_ip ~/Dropbox/

Then name and save the file, make it executable and add it to crontab.

No comments:

Post a Comment