Ubuntu – How to auto-scan any plugged in usb storage device with clamav

clamav

I'd like to do an automatic virus scan on any plugged in usb device using ClamAV. I'm using Ubuntu 12.04.

The closest thing I found was:

The first one is not working for me and the second one seems to target a known device.

Is there a tutorial around I've missed? Or can I get some help with udev rules that apply to any usb storage device added? Currently nothing seems to do anything.

Best Answer

This is an automated script. Just run it as root. You can change the command executed by editing /usr/bin/doOnUSBinsert.

#!/bin/bash
#doOnUSBinsert_0.2.sh
#Author : Totti
# Make it executable by running 'sudo chmod  x doOnUSBinsert_0.2.sh'


if ! [ -f /etc/udev/rules.d/80-doOnUSBinsert.rules ]
then        # rule not added
   cp "$0" /usr/bin/doOnUSBinsert
   chmod u x /usr/bin/doOnUSBinsert

#   echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/path/to/script.sh"' | sudo tee     /etc/udev/rules.d/80-clamscan.rules
   echo 'SUBSYSTEM=="usb", ACTION=="add", RUN ="/usr/bin/doOnUSBinsert & "' | tee     /etc/udev/rules.d/80-doOnUSBinsert.rules
   if  [ $? -eq 0 ]
   then
     echo 'Rule Successfully added. See file "/usr/bin/doOnUSBinsert" if you wish to edit the command'
     exit 0
    else
     echo 'ERROR while adding rule'
     exit 1
   fi
fi



lfile="/tmp/doOnUSBinsert.log"     # udev
lfile2="/tmp/clamscanFromUdev.log"   # clamscan
lfile3="/tmp/doOnUSBinsert_mount.log"   # mount


main ()
{
sleep 12  # let the partitions to mount

   #cat /proc/$$/environ | tr '�' 'n' >> /tmp/udevEnvirn.txt
echo "found $ID_SERIAL"   >> "$lfile"
  cat /etc/mtab | grep "^$part_c"   >> "$lfile.3"

if [ "$ID_SERIAL"x = 'x' ]
then
 echo "Exiting on empty ID_SERIAL"   >> "$lfile"
 exit 1
fi

#Eg: ID_SERIAL --> /dev/disk/by-id/usb-sandisk....42343254343543
#i=0
echo 'searching partitions'   >> "$lfile"

for partitionPath in  $( find /dev/disk/by-id/ -name "*$ID_SERIAL*part*" )
do
  echo "current partition = $partitionPath"   >> "$lfile"
 # part[i  ]="$( readlink -f "$partition" )"        # Eg Output: /dev/sdb1     , /dev/sdb2
  part_c="$( readlink -f $partitionPath )"   
  mpoint="$( cat /etc/mtab | grep "^$part_c"  | awk '{print $2}' )"

  echo "partitionPath= $partitionPath, part = $part_c, mountpoint=  $mpoint"  >>     "$lfile"

  echo "Scaning -->  $mpoint"  >> "$lfile.2"
  ############################################
  clamscan -r --bell "$mpoint"/*  >> "$lfile.2"
  #############################################
done
}


main &
echo ______________________________________  >> "$lfile"
exit 0