1. Task Definition
Today, we’ll write a real script that checks a website’s availability and logs the result to a log file, then automates its execution using cron.
What are we trying to do?
We’ll be creating a bash script that:
- Checks the availability of a specified website using
ping. - Logs the result of the check into a log file, including the time and date.
- Runs this script automatically every 5 minutes using
cron.
Why is this important?
In the real world, monitoring the availability of websites and servers is one of the key tasks for system administrators. For example, if your website (or server) suddenly stops responding, you’d want to know about it as soon as possible. This kind of scenario is not just useful for monitoring but also for job interviews or work practice.
2. Step 1: Writing a Simple Bash Script
Let's start by writing the basic bash script. Here's a step-by-step explanation of what it will do:
- We'll set the website address to check.
- Use
pingto try sending a request to the server. - Check if an accessible response was returned.
- Save the result to a log file.
Let's create the file site_check.sh:
#!/bin/bash
# Define the website address
WEBSITE="example.com"
# File to log results
LOG_FILE="/var/log/site_status.log"
# Check website availability using ping
if ping -c 1 $WEBSITE &> /dev/null; then
# If the site is reachable
echo "$(date): $WEBSITE is reachable" >> $LOG_FILE
else
# If the site is unreachable
echo "$(date): $WEBSITE is unreachable" >> $LOG_FILE
fi
Code Explanation:
#!/bin/bash— tells that this script should be executed using Bash.WEBSITE="example.com"— the address of the website to check. You can replaceexample.comwith any site or server you want to monitor.ping -c 1 $WEBSITE— sends one (-c 1) packet to the specified website. If the site responds, the command exits with code 0. If not, it exits with an error.&> /dev/null— redirects standard output and errors to the "black hole" (we don't want to see thepingoutput in the console).$(date)— adds the current date and time to the message.>> $LOG_FILE— appends the result to the log file.
3. Step 2: Running the script manually
Before automating the script execution, let's make sure it works.
Save the script to a file named
site_check.sh.Make it executable:
chmod +x site_check.shRun it:
sudo ./site_check.sh
After executing the script, open the file /var/log/site_status.log to ensure the result of the check is logged. Use the following command:
cat /var/log/site_status.log
If everything works, you should see a line like this:
Mon Oct 30 14:35:22 UTC 2023: example.com is reachable
4. Step 3: Setting Up Automatic Execution with cron
We already know that cron lets us schedule tasks. Now we'll configure cron so our script runs every 5 minutes.
Editing crontab
Open the crontab editor:
crontab -e
Add the following line:
*/5 * * * * /path/to/site_check.sh
Explanation:
*/5— specifies that the task should run every 5 minutes./path/to/site_check.sh— full path to our script. Make sure it's correct. For example, if the script is in the user's home directory, the path might look like/home/your_username/site_check.sh.
After saving the changes, cron will start running the script every 5 minutes. To confirm the task has been added, run:
crontab -l
5. Step 4: Checking cron functionality
Now let's verify if the automation works. Wait for 5-10 minutes and open the log file again:
cat /var/log/site_status.log
You should see new entries being updated every 5 minutes. For example:
Mon Oct 30 14:35:22 UTC 2023: example.com is reachable
Mon Oct 30 14:40:22 UTC 2023: example.com is reachable
Mon Oct 30 14:45:22 UTC 2023: example.com is reachable
6. Typical Questions and Errors Breakdown
Ping returns 'Permission denied' error
If you're running the script as a regular user, it might not have enough permissions. Run the script with
sudoor add execute permissions.Log file isn't being created
Make sure the path to the log file (
/var/log/site_status.log) is correct and your user has write permissions in that directory. If the file doesn't exist, create it manually using:sudo touch /var/log/site_status.log sudo chmod 666 /var/log/site_status.logcronisn't running the scriptCheck if the
cronservice is active:sudo systemctl status cronIt should have the status
active (running). If it's stopped, start it:sudo systemctl start cronThe script runs manually but doesn't execute via cron
Make sure the path to the script and all used files is specified completely. In
cronjobs, environment variables (e.g.,$PATH) might be different. It's better to use absolute paths.
7. Improvements and Additional Tasks
Website Filtering
Expand the script to check the availability of multiple websites. For example:
WEBSITES=("example.com" "google.com" "stackoverflow.com")
for SITE in ${WEBSITES[@]}; do
if ping -c 1 $SITE &> /dev/null; then
echo "$(date): $SITE is reachable" >> $LOG_FILE
else
echo "$(date): $SITE is unreachable" >> $LOG_FILE
fi
done
Sending Notifications
Add sending notifications if a website is unavailable. For example, using the mail command to send an email:
# Email notification
if ! ping -c 1 $WEBSITE &> /dev/null; then
echo "$WEBSITE is down!" | mail -s "Website Check Alert" your_email@example.com
fi
Cyclic Logging
Limit the log file size to, say, 1 MB. If the file gets too large, rename it (like an archive) and start a new log.
Congrats! Now you know how to use bash scripts and cron to automate real-world tasks. These skills are especially valuable for DevOps engineers and system administrators.
GO TO FULL VERSION