Tag Archives: linux

Using ClamAV Daily Scan and Slack Notification

Taking a little inspiration from HowtoForge I was able to create a simple daily ClamAV scanner that sends a slack notification if any viruses are found.

#!/bin/bash
# set -x
# Clam Scan Details
CLAMAV="/usr/bin/clamdscan"
LOGFILE="/tmp/clamav-daily-scan.log"
DIRECTORIES="/home /etc /opt"

# Host Details
HOST=$(hostname)
IP=$(hostname -I)
HOST_ENV=$(env)

# Slack Webhook
SLACK_WEBHOOK="https://hooks.slack.com/services/XXXXXXXXX/XXXXXXXXX/xxxxxxxxxxxxxxxxxxxxxxxx"
SLACK_CHANNEL="#random"
SLACK_BOTNAME="clamav"
SLACK_ICON=":skull:"

[ ! -f $CLAMAV ] && echo "Missing $CLAMAV. Please check path or install first" && exit 1

function scan() {
  [ -f $LOGFILE ] && rm $LOGFILE
  $CLAMAV $DIRECTORIES --fdpass --log=$LOGFILE --infected --multiscan
}

function notify() {   
  # Get "Infected lines"
  MALWARE=$(tail "$LOGFILE"|grep Infected|cut -d" " -f3)
  if [ "$MALWARE" -ne "0" ]; then
    VIRUSES_FOUND=$(cat "$LOGFILE" | grep FOUND | cut -d" " -f2 | sort -u)
    MESSAGE="Found ${MALWARE} infected files on daily virus scan."
    SLACK_PAYLOAD="payload={\"channel\":\"${SLACK_CHANNEL}\",\"icon_emoji\":\":skull:\",\"username\":\"${SLACK_BOTNAME}\",\"attachments\":[{\"fallback\":\"${MESSAGE}\",\"color\":\"#333\",\"pretext\":\"${MESSAGE}\",\"fields\":[{\"title\":\"Host\",\"value\":\"${HOST}\",\"short\":true},{\"title\":\"Log Location\",\"value\":\"${LOGFILE}\",\"short\":true},{\"title\":\"Host IP(s)\",\"value\":\"${IP}\",\"short\":false},{\"title\":\"Viruses found\",\"value\":\"${VIRUSES_FOUND}\",\"short\":false}]}]}" 
    curl -X POST --data-urlencode "${SLACK_PAYLOAD}" "${SLACK_WEBHOOK}"
  fi
}

case "$1" in
  scan|s)
    scan
    ;;
  notify|n)
    notify
    ;;
  *)
    scan
    notify
esac

When a virus is found it produces a slack notification that looks like this: