您的位置:首页 > 编程语言 > Python开发

为python添加magic进行文件类型识别

2015-12-25 10:41 585 查看
最近想看看cuckoo里的文件识别功能是怎样实现的,翻了cuckoo源码,发现其对文件格式的判断代码如下:

def _get_filetype(self, data):
"""Gets filetype, uses libmagic if available.
@param data: data to be analyzed.
@return: file type or None.
"""
if not HAVE_MAGIC:
return None

try:
ms = magic.open(magic.MAGIC_NONE)
ms.load()
file_type = ms.buffer(data)
except:
try:
file_type = magic.from_buffer(data)
except Exception:
return None
finally:
try:
ms.close()
except:
pass

return file_type


其中用到了libmagic库里的magic,libmagic是一个根据文件头识别文件类型的开发库,python可以利用该库很方便地实现对文件格式的判断。记录一下安装过程。安装环境:winxp + python 2.7

安装magic 模块:
  1、安装pycparser-2.14 链接: https://pypi.python.org/pypi/pycparser
  2、安装VCForPython,链接: http://aka.ms/vcpython27   3、安装cffi模块,链接: https://pypi.python.org/pypi/cffi/#downloads
  4、安装libmagic 链接: https://pypi.python.org/pypi/python-libmagic
  5、安装file,安装之后向环境变量path添加: ..\GnuWin32\bin
  6、安装magic模块 链接: https://github.com/ahupp/python-magic
    测试 import magic成功即可
  More details see https://github.com/ahupp/python-magic

利用卡巴斯基的扫描结果对样本进行分类整理(包含文件类型识别)的程序见:https://github.com/Viwilla/ClassifySamples
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: