IT Automation Using Cronjob

IT Automation Using Cronjob

Prerequisite

  • Basic understanding of Linux
  • Basic understanding of the Commandline
  • Basic Understanding of Bash Scripting

Expectations

  • Learns Automation
  • Learns how to send emails using the command line
  • Learns how to Automate scheduled tasks using crontab

In this article, I will be working through the process of automating scheduled tasks using crontab.

What Is IT Automation?

IT Automation is the process of replacing manual tasks with automatic ones, the goal of IT Automation is to make a process faster, easy to use and reusable. IT Automation reduces human error within tasks and leads to increased efficiency in IT tasks and processes.

What is Crontab

Crontab is a tool for automating scheduled tasks It is UNIX-commandline utility that contains a list of tasks to be run at specific times. An example of this task is a script that is written to delete temporary files every week in order to save disk space.

  • A cron jobis included within an Unix-based operating system, it is a Linux command used to create scheduled jobs.
  • The cron daemon is a long-running process that executes commands at specific dates and times, A daemon is a process that runs in the background. Cron reads the configuration files(Crontab) for a list of tasks to execute.
  • Crontab is a file that contains the list of cronjobs to be run.

For this article, I will work through a task that requires me to send an email to my manager about my daily tasks by 8 am. Using crontab I schedule your Linux machine to send the email by specifying the time I want the command to be executed, how I want it to be executed and the path to the file that contains the command I want executed.

Each entry in a crontab file consists of six fields, specifying in the following order:

cron.png

Where no value is put in, an asterisk is used.

  0 * * * * bash /home/lola/Documents/AltSch/cronjob/altsch.sh
  • This is a command that executes at the '0th' minute of every hour
  • It uses bash to execute the command
  • The last part of the command is the path to the file it is going to execute.

Another example is:

* 0 * * * /usr/bin/php /var/home/html/crontab/cron.php
  • This is a command that executes at the '0th' hour of every day, 12am is counted as the zeroth hour
  • It uses PHP to execute the file, and php is located in my binaries folder, /bin
  • The last part of the command is the path to the file it is going to execute
20 21 * * 5 bash /home/example/scripts/example.sh
  • This is a command that executes at the '20th' minute of every hour, of every '21st' hour every '5th' day of the week, that is, 21:20 every Friday.
  • It uses 'bash' to execute the file
  • The last part of the command is the path of the file it is going to execute.

To find out more information on how to schedule the time for your cronjobs check out Cronjob time

The crontab command creates a crontab file containing commands and instructions for the cron daemon to execute. You can use the crontab command with the following options, this commands will open up and editor in your terminal. To exit check the commands at the bottom of your screen:

  • crontab -e Edit your crontab file or create one if it doesn't already exist.
  • crontab -l Display your crontab file listing your current cronjobs.
  • crontab -r Remove your crontab file. (Be careful with this command as it deletes your crontab files).




How to send Emails through the command line

We want to be able to send emails to an email address using the command line. For this task we have to confirm our time and date is set to our current timezone. To check the settings, use the command: timedatectl --help This lists out the commands you can use to edit the time/date/timezone.

  • 'status' shows the current time settings

    sudo timedatectl status
    
  • 'set-time TIME' sets the system time to the 'TIME' indicated

    sudo timedatectl set-time 12:00
    
  • 'list-timezones' lists the known time zones

    sudo timedatectl list-timezones
    
  • 'set-timezone ZONE' sets the system time zone to the 'ZONE' indicated
    sudo timedatectl set-timezone Africa/Lagos
    

When the timezone has been set, we will then install Secure Simple Mail Transfer Protocol (SSMTP) which is a program used to deliver emails from a computer to a mail hub (examples are Gmail, Hotmail, yahoo mail...) SSMTP is sometimes paired with other libraries such as Mutt and Mailutils.

To Install Mutt

Mutt is a command line Email Client that is used to send Emails with attachments.

sudo apt-get install mutt

To Install Mailutils

sudo apt-get install mailutils

To Install SSMTP

sudo apt update
sudo apt-get install ssmtp

To configure SSMTP

Recall that /etc contains configuration files hence to configure ssmtp, on the command line, navigate to the ssmtp configuration file and open it.

nano /etc/ssmtp/ssmtp.conf

Edit the contents of your ssmtp.conf to include the following:

- FromLineOverride=YES
- root=youremailadress@gmail.com
- mailhub=smtp.your-domain.com:587
- hostname=yourhostname
- AuthUser=youremailaddress@gmail.com
- AuthPass=your-Gmail-app-password
- UseSTARTTLS=YES

Your configuration file should look like this:

ssmtp.png

  • Your hostname can be gotten by typing hostname on the command line
  • Your Gmail app password can be gotten by following the steps on this page. Before that, you have to have your two-factor-authentication setup 2FA setup guide.
  • Remember when adding your password to the authentication file leave no space in between.

Now your system is set up to send emails from the command line. To confirm:

  • Create a file called testing.txt
    touch testing.txt
    
  • Add content to it
nano testing.txt

Subject: This is a test

What does the fox say?
  • Save and close the file then send an email with the file
ssmtp -v youremailaddress@gmail.com < testing.txt

If everything is fine, you should see:

[<-] 220 smtp.gmail.com ESMTP kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp
[->] EHLO mfon
[<-] 250 SMTPUTF8
[->] STARTTLS
[<-] 220 2.0.0 Ready to start TLS
[->] EHLO mfon
[<-] 250 SMTPUTF8
[->] AUTH LOGIN
[<-] 334 VXNlcm5hbWU6
[->] bWZvbm50YTA3QGdtYWlsLmNvbQ==
[<-] 334 UGFzc3dvcmQ6
[<-] 235 2.7.0 Accepted
[->] MAIL FROM:<mfybaby@mfon>
[<-] 250 2.1.0 OK kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp
[->] RCPT TO:<*****@gmail.com>
[<-] 250 2.1.5 OK kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp
[->] DATA
[<-] 354  Go ahead kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp
[->] Received: by mfon (sSMTP sendmail emulation); Tue, 27 Sep 2022 10:37:31 +0100
[->] From: "MfyBaby" <mfybaby@mfon>
[->] Date: Tue, 27 Sep 2022 10:37:31 +0100
[->] 
[->] .
[<-] 250 2.0.0 OK  1664271553 kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp
[->] QUIT
[<-] 221 2.0.0 closing connection kl14-20020a170907994e00b007813968e154sm504859ejc.86 - gsmtp

You should also get an email as such:

fox.png






Editing Your Bash File

For simplicity, I created two bash files. One bash file will send the contents of my memory information to another file. The second file will send the contents of said file to my email address /n /n

How To Send the contents of one file to another

Sending contents of one command to another is done using the sign, > Hence, create a file called content.sh

touch content.sh && nano content.sh

In the file;

#!/bin/bash

cat /proc/meminfo > result.sh

This is a bash script that prints the contents of the command, cat /proc/meminfo into the file called result.sh Remember to make your file executable using chmod +x content.sh




How to Send the contents of my file to Email Address

This was done using a bash script. Recall that the result of my log information was saved to a file called result.sh in the previous step. In this step, I will be creating another file called email.sh in the same folder. This file will contain a script that when run will send the contents of result.sh to a specified email address. In your terminal in the same folder as you've been, type:

touch email.sh && nano email.sh

This will create a file called email.sh and open it up. In the file, type:

#!/bin/bash

path=result.sh

email=myemailaddress@gmail.com

echo "Here is my midnight report" | mutt -a ${path} -s "Midnight ram report" -- ${email} && sudo rm -f ${path}
  • The first line called a hashbang or shebang, says that this script should be run through the /bin/bash shell
  • The next two lines define variables path and email. The path variable is the path where my result.sh is located. This might differ for you if your file is located in a different folder. The email variable holds my email address.
  • The last line contains what should be contained in my email, Mutt attaches the file @path and sends it to the email address indicated. The file is then removed from the path after that.

    To confirm that this script runs as expected, in your terminal, type:
    chmod +x email.sh
    ./email.sh
    

The first line makes the email.sh file executable and the second line executes it. If all is correct, you should get an email containing the result.sh

result.png




Writing Cronjob For Tasks

To list out the current cronjobs running:

crontab -l

If you have an existing cronjob, it will be displayed here.

To edit or add a crontab:

crontab -e

In this file we will type out the cronjobs we want to be executed using the format;\

cron.png

For the first job where we want the contents of our log file to be sent to a file called result.sh every hour:

0 * * * * bash /home/Documents/AltSch/cronjob/content.sh

bash will be used to execute this file every hour at the path indicated.

P.S Remember you can visit Crontab Guru to get the syntax of your cronjob timing right.

For the Second job where we want the contents of result.sh to be sent to our email address at midnight every day:

* 0 * * * bash /home/Documents/AltSch/cronjob/email.sh

Take note that by default, cron sends an email to the owner of the crontab file when it executes. While this serves as a convenient way to keep track of tasks, regular or minor tasks can fill up your inbox pretty quickly.


Conclusion

In this article we have learned what crontab is, how a cronjob works, and how to send emails from the command line. Crontab can be used to write scripts to execute daily tasks instead of manually doing them. This saves time, improves efficiency, and reduces the percentage of error.