Python magic.MagicException() Examples

The following are 4 code examples of magic.MagicException(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module magic , or try the search function .
Example #1
Source File: pescanner.py    From CapTipper with GNU General Public License v3.0 6 votes vote down vote up
def get_filetype(data):
    """There are two versions of python-magic floating around, and annoyingly, the interface 
    changed between versions, so we try one method and if it fails, then we try the other.
    NOTE: you may need to alter the magic_file for your system to point to the magic file."""
    if sys.modules.has_key('magic'):
        try:
            ms = magic.open(magic.MAGIC_NONE) 
            ms.load() 
            return ms.buffer(data)
        except:
            try:
                return magic.from_buffer(data)
            except magic.MagicException:
                magic_custom = magic.Magic(magic_file='C:\windows\system32\magic')
                return magic_custom.from_buffer(data)
    return '' 
Example #2
Source File: forms.py    From Spirit with MIT License 5 votes vote down vote up
def clean_file(self):
        file = self.cleaned_data['file']

        if not magic:
           raise forms.ValidationError(_("The file could not be validated"))

        # Won't ever raise. Has at most one '.' so lstrip is fine here
        ext = os.path.splitext(file.name)[1].lstrip('.').lower()
        if ext not in settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE:
            raise forms.ValidationError(
                _("Unsupported file extension %(extension)s. "
                  "Supported extensions are %(supported)s.") % {
                    'extension': ext,
                    'supported': ", ".join(
                        sorted(settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.keys()))})

        try:
            if isinstance(file, TemporaryUploadedFile):
                file_mime = magic.from_file(file.temporary_file_path(), mime=True)
            else:  # In-memory file
                file_mime = magic.from_buffer(file.read(), mime=True)
        except magic.MagicException as e:
            logger.exception(e)
            raise forms.ValidationError(_("The file could not be validated"))

        mime = settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.get(ext, None)
        if mime != file_mime:
            raise forms.ValidationError(
                _("Unsupported file mime type %(mime)s. "
                  "Supported types are %(supported)s.") % {
                    'mime': file_mime,
                    'supported': ", ".join(
                        sorted(settings.ST_ALLOWED_UPLOAD_FILE_MEDIA_TYPE.values()))})

        return file 
Example #3
Source File: InfoExtractor.py    From codex-backend with MIT License 5 votes vote down vote up
def MIME_TYPE(data, mime=True):
    try:
        return magic.from_buffer(data, mime=mime)
    except magic.MagicException:
        return "none/none" 
Example #4
Source File: searching.py    From osspolice with GNU General Public License v3.0 4 votes vote down vote up
def skip_lib(main, lib_path):
    logger.debug("Checking lib %s", lib_path)
    try:
        if not os.path.isfile(lib_path):
            logger.error("skipping %s: not a file", lib_path)
            return True

        elif not os.path.exists(lib_path):
            logger.error("skipping %s: doesn't exist", lib_path)
            return True

        elif main.ignore_scanned and main.rrc and main.rrc.handle().exists(lib_path):
            logger.error("Skipping processed lib_path %s", lib_path)
            return True

        try:
            import magic
            lib_info = magic.from_file(lib_path).split(',')
            lib_type = lib_info[0]
            if lib_type != "ELF 32-bit LSB shared object" and "ELF 32-bit" not in lib_type:
                logger.error("skipping %s: not a ELF 32-bit shared object", lib_path)
                return True
            lib_arch = lib_info[1]
            if lib_arch != " ARM":
                logger.error("skipping %s: not an ARM exectable", lib_path)
                return True

            return False

        except ImportError as ie:
            logger.error("skipping %s: %s", lib_path, str(ie))
            return True

        except magic.MagicException as me:
            logger.error("skipping %s: magic exception %s", lib_path, str(me))
            return True

    except Exception as e:
        exc_type, exc_obj, exc_tb = sys.exc_info()
        fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]
        logger.error("[%s, %s, %s] skipping %s: %s", exc_type, fname, exc_tb.tb_lineno, lib_path, str(e))
        return True


###########################################################
# Lookup items by features
###########################################################