Linux cron job

This pages shows how to add a cron job for current user. And also shows how to send email in Amazon Linux through sSMPT.

There are 2 ways to add job,

  • There are cron folders under /etc, such as /etc/cron.hourly, /etc/cron.daily, /etc/corn.weekly and /etc/cron.monthly. Add shell script under these folders will run hourly/daily/weekly/monthly correspondingly.
  • Create a specific schedule for particular user, we will focus on this way.

First, exectue below command, will create a new cron file for current user under /var/spool/cron, the file name is same with current username

crontab -e

Second, edit generated cron file adding below line, the sendemail job will be executed every 5 minutes,

*/5 * * * * sh /root/report/sendemail.sh

In the sendemail.sh, which send email through sSMPTP.
First, install the sSMTP,

yum install sSMTP


Second, edit /etc/ssmtp/ssmtp.conf, add below,

mailhub=smtp.gmail.com:587
UseSTARTTLS=YES
AuthUser=yourusername@gmail.com
AuthPass=yourpassword

Third, the sendemail.sh looks like,

now=$(date +%m/%d/%Y)

dir=/root/report/

echo "From: OverriddenFrom<yourusername@gmail.com>" > $dir/email.txt
echo "Subject: email title $now" >> $dir/email.txt
echo >> $dir/email.txt
echo email content >> $dir/email.txt
echo >> $dir/email.txt
echo "Generated at $(date +'%m/%d/%Y %H:%M:%S')" >> $dir/email.txt

/usr/sbin/ssmtp recipient@gmail.com < $dir/email.txt

Note, the From: must be format as OverriddenFrom<yourusername@gmail.com>, if use OverriddenFrom only, gmail seems reject it, and override it to yourusername only.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s