Schedule scan with cron using crontab -e
In this step, we will schedule our scan.sh
script to run automatically using cron
. cron
is a time-based job scheduler in Linux-like operating systems. It allows you to schedule commands or scripts to run at specific times, dates, or intervals.
To schedule a task with cron
, we use the crontab
command. The crontab -e
command opens the crontab file in a text editor (usually nano
in the LabEx environment).
In your terminal, type the following command:
crontab -e
If this is the first time you're using crontab
, you might be prompted to select an editor. Choose nano
by selecting the corresponding number.
The crontab file contains a list of cron jobs, each on a separate line. Each line consists of six fields:
minute hour day_of_month month day_of_week command
- minute: The minute of the hour when the job will run (0-59).
- hour: The hour of the day when the job will run (0-23).
- day_of_month: The day of the month when the job will run (1-31).
- month: The month of the year when the job will run (1-12).
- day_of_week: The day of the week when the job will run (0-6, where 0 is Sunday).
- command: The command to execute.
For example, to run the scan.sh
script every minute, add the following line to the crontab file:
* * * * * /home/labex/project/scan.sh
This line means:
*
: Every minute
*
: Every hour
*
: Every day of the month
*
: Every month
*
: Every day of the week
/home/labex/project/scan.sh
: The command to execute (the full path to our script)
Important: It's generally not a good idea to run scans every minute in a real-world scenario, as it can put a strain on the network and the target devices. For testing purposes in this lab, running it every minute is acceptable.
To save the changes, press Ctrl+X
, then Y
to confirm, and then Enter
to save the file.
You should see a message like "crontab: installing new crontab". This means the cron job has been successfully scheduled.
Cron jobs typically run in the background without displaying any output. To see the output of the scan.sh
script, you can redirect it to a file. For example, to redirect the output to a file named scan.log
in your ~/project
directory, you can modify the cron job entry as follows:
* * * * * /home/labex/project/scan.sh > /home/labex/project/scan.log 2>&1
The > /home/labex/project/scan.log
part redirects the standard output to the scan.log
file, and 2>&1
redirects the standard error to the same file.