ClamAV script for automatic scanning and email notifications

I will give an example of a script for scanning and email notifications when infected files are detected.

The implication is that ClamAV is installed and the server can send emails.

Script content:

#!/bin/bash
LOGFILE="/var/log/clamav/clamav-$(date +'%Y-%m-%d').log";
EMAIL_MSG="Please see the log file attached";
EMAIL_FROM="test@ixnfo.com";
EMAIL_TO="test@ixnfo.com";
DIRTOSCAN="/var/www /var/vmail";

for S in ${DIRTOSCAN}; do
 DIRSIZE=$(du -sh "$S" 2>/dev/null | cut -f1);

 echo "Starting scan of "$S" directory.
 Directory size: "$DIRSIZE".";

 clamscan -ri "$S" >> "$LOGFILE";
 #clamscan -ri --remove "$S" >> "$LOGFILE";

 #find /var/log/clamav/ -type f -mtime +30 -exec rm {} \;
 MALWARE=$(tail "$LOGFILE"|grep Infected|cut -d" " -f3);

 if [ "$MALWARE" -ne "0" ];then
 echo "$EMAIL_MSG"|mail -a "$LOGFILE" -s "Malware Found" -r "$EMAIL_FROM" "$EMAIL_TO";
 fi 
done

exit 0

Make the file executable:

chmod 0755 /root/scripts/clamscan.sh

When the script is run, the specified directories /var/www and /var/vmail will be scanned, logs will be saved to /var/log/clamav/, if the word “Infected” appears in the logs, the log file will be sent to the specified email. In order for the antivirus to also remove threats, add “–remove” as shown in the commented line, also if lopgrotate is not configured to delete files, then uncomment the command starting with “find”, which will delete log files older than 30 days.

To start automatically, for example, daily at one in the morning, we add the following term in /etc/crontab:
1 1 * * * root /root/scripts/clamscan.sh > /dev/null 2>&1

See also my articles:
Installing and Configuring Postfix
Using and configuring CRON
Installing and using ClamAV antivirus software
How to start ClamAV scanning from the command line on the cPanel server

Leave a comment

Leave a Reply