Login

Scan uploaded file for viruses with clamav

Author:
uandt
Posted:
May 27, 2008
Language:
Python
Version:
.96
Score:
4 (after 4 ratings)

A clean_<fieldname>() method in a form subclass as described here. Scans the field named file for viruses.

My version of python-clamav does not support scanning of buffers. That is why I go through the hassle of saving the file to a temporary one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
def clean_file(self):
    file = self.cleaned_data.get('file', '')
    #check a file in form for viruses
    if file:
        from tempfile import mkstemp
        import pyclamav
        import os
        tmpfile = mkstemp()[1]
        f = open(tmpfile, 'wb')
        f.write(file.content)
        f.close()
        isvirus, name = pyclamav.scanfile(tmpfile)
        os.unlink(tmpfile)
        if isvirus:
            raise forms.ValidationError( \
            "WARNING! Virus \"%s\" was detected in this file. \
            Check your system." % name)

    return file

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 6 months ago

Comments

Please login first before commenting.