Home MiscellaneousHow to Automate ClamAV Virus Scans with Cron Jobs on Linux ?

How to Automate ClamAV Virus Scans with Cron Jobs on Linux ?

by Bella

Clam AntiVirus (ClamAV) is a free, open-source, cross-platform antivirus toolkit designed to detect various types of malware, including viruses and trojans. It is widely used on mail servers for scanning incoming emails and is compatible with multiple operating systems such as Linux, BSD, macOS, Solaris, and more.

In this guide, we’ll walk through how to install ClamAV and automate virus scanning using cron jobs on a Linux server (tested on Red Hat Enterprise Linux).

Step 1: Install ClamAV

Install ClamAV and required components using the package manager:

yum install -y clamav clamav-db clamd

Start the ClamAV daemon:

systemctl start clamd

This setup also enables automatic virus definition updates using freshclam.

Step 2: Create a Daily Cron Job for Scanning

To automate scanning, create a script inside the cron daily directory:

vi /etc/cron.daily/clamscan_daily

Step 3: Add the Scan Script

Paste the following script into the file:

#!/bin/bash# Email configuration
EMAIL="alert@domain.com"
SUBJECT="ClamAV Alert on $(hostname)"# Log file
LOG="/var/log/clamav/daily_scan.log"# Run ClamAV scan
clamscan -r / \
--exclude-dir="^/proc" \
--exclude-dir="^/sys" \
--exclude-dir="^/dev" \
--quiet \
--infected \
--log=$LOG# Check for infections
if grep -q "Infected files: [1-9]" $LOG; then
MAILFILE=$(mktemp /tmp/clamav_alert.XXXXXX) echo "To: $EMAIL" >> $MAILFILE
echo "From: alert@domain.com" >> $MAILFILE
echo "Subject: $SUBJECT" >> $MAILFILE
echo "" >> $MAILFILE
echo "Malware detected on $(hostname). See details below:" >> $MAILFILE
echo "" >> $MAILFILE
tail -n 50 $LOG >> $MAILFILE sendmail -t < $MAILFILE
fi

Step 4: Set Proper Permissions

Make the script executable:

chmod +x /etc/cron.daily/clamscan_daily

How It Works

  • The script runs automatically once a day via cron
  • ClamAV scans the entire system while excluding critical directories
  • Scan results are saved to a log file
  • If any infected files are detected, an email alert is sent

Conclusion

Automating ClamAV scans using cron ensures continuous protection for your server without manual intervention. This setup helps detect threats early and provides instant alerts, improving overall system security.

For advanced configuration or server security support, you can reach out to SupportPRO Server Admin for expert assistance.

Facing issues?

Our technical support
engineers can solve it.

Contact Us today!
guy server checkup

You may also like

Leave a Comment