Introduction

This script uses ClamAV (clamscan) to scan all cPanel user directories for malware and sends an email alert if infections are found. It can be scheduled via cron for regular automated scanning.

Prerequisites

Before using this script, ensure:

  • ClamAV is installed (clamscan, freshclam)
  • Mail service is configured on the server
  • Directory /root/clamreport/ exists
  • Root or sudo access

Script

#!/bin/bash# Email to receive alertsEMAIL="your-email@example.com"# Temporary fileTMP_FILE="/tmp/clamscan_report.txt"# Report directoryREPORT_DIR="/root/clamreport"mkdir -p $REPORT_DIR# Flag to check infectionsINFECTED=0# Update virus definitions/usr/local/clamav/bin/freshclam >/dev/null 2>&1# Loop through all cPanel usersfor user in $(cut -d: -f2 /etc/trueuserdomains | xargs); do    SCAN_PATH="/home/$user/public_html"    if [ -d "$SCAN_PATH" ]; then        /usr/local/clamav/bin/clamscan -ir "$SCAN_PATH" > "$TMP_FILE"        if grep -q "FOUND" "$TMP_FILE"; then            grep "FOUND" "$TMP_FILE" > "$REPORT_DIR/$user.report"            INFECTED=1        fi    fidone# Send alert if infection foundif [ $INFECTED -eq 1 ]; then    SUBJECT="CLAMAV ALERT on $(hostname)"    MESSAGE="Malware detected on server $(hostname). Check reports in $REPORT_DIR."    echo "$MESSAGE" | mail -s "$SUBJECT" "$EMAIL"fi# Cleanuprm -f "$TMP_FILE"

How to Schedule via Cron

Daily Scan

crontab -e

Add:

0 2 * * * /root/clamscan.sh

Runs daily at 2:00 AM

Weekly Scan

0 3 * * 0 /root/clamscan.sh

Runs every Sunday at 3:00 AM

Notes

  • Scanning large servers may consume high CPU → schedule during low traffic
  • Consider using clamdscan for better performance (daemon mode)
  • Ensure email alerts are working (mail command configured)
  • Reports are saved per user in /root/clamreport/

Conclusion

This automated ClamAV script helps detect malware across all cPanel user accounts and ensures timely alerts. Scheduling it via cron improves server security with minimal manual effort.

Leave a Reply