When creating cron tasks on Linux many people do not realize that the output from the cron will logged and without redirection will sent to the user running the cron task’s email. In many cases this is the root user or if an alias has been set in /etc/aliases then the email will be sent to the user configured to receive roots email in the aliases file. Specifically on Backtrack Linux the root users email is redirected to bt5 by default and that user does not exist so the email will simply bounce. Below we describe a better way to redirect the cron tasks output into a log file which could be useful down the road.
Depending on how much information needs to be redirected to a log file you will either want to create a new log file or redirect the output to syslog. Typically syslog is the best place to output this information because it is a log file that is already redirected and used for lots of different information. A great way to interface with syslog on Backtrack Linux or Ubuntu Linux is to use the logger command and tag the output accordingly so it can easily be parsed from the log file if necessary in the future. The example below shows a simple cronjob that is backing up KeepNote notes on a daily basis and redirecting the output from the backup script to syslog.
Cron Task Output Redirected To Syslog On Backtrack Linux:
- 33 3 * * * /home/backup/keepnote-backup.sh 2>&1 | /usr/bin/logger -t keepnote_backup
The above cron will run every morning at 3:33AM and the output is piped ( with | ) to the logger command which then tags the output with “keepnote_backup” and inserts it into /var/log/syslog. Each time the cron runs anything that is output from the script will end up in syslog as shown in the below example syslog snip.
View Of Cronjob Output To Syslog On Backtrack Linux:
- Dec 20 3:33:01 bt CRON[32080]: (root) CMD (/home/backup/keepnote-backup.sh 2>&1 | /usr/bin/logger -t keepnote_backup)
- Dec 20 3:33:01 bt keepnote_backup: Sun Dec 20 16:32:01 EST 2012
- Dec 20 3:33:01 bt keepnote_backup: Archiving KeepNotes From /root/notes to /home/backup/keepnote/keepnotes-bt-2012-12-20_16:32:01.tgz
- Dec 20 3:33:01 bt keepnote_backup: /bin/tar: Removing leading `/' from member names
- Dec 20 3:33:01 bt keepnote_backup: KeepNotes Backed Up
In the above syslog example the cron task outputs its status messages and any errors/warnings to syslog with the keepnote_backup tag. The tag makes things easier to troubleshoot down the line when you are looking back through syslog history you can simply grep for keepnote_backup and receive any messages related to this specific cronjob.