Python之基于十六进制判断文件类型
核心代码:
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- # @Author : suk
- import struct
- from io import BytesIO
- # 支持文件类型
- # 用16进制字符串的目的是可以知道文件头是多少字节
- # 各种文件头的长度不一样,少则2字符,长则8字符
- def typeList(types):
- type_dict = {'jpg': ['FFD8FFE000104A464946'],
- 'png': ['89504E470D0A1A0A0000'],
- 'gif': ['47494638396126026F01'],
- 'tif': ['49492A00227105008037'],
- 'bmp': ['424D8E1B030000000000'],
- 'dwg': [''],
- 'html': ['3C21444F435459504520'],
- 'htm': ['3C21646F637479706520'],
- 'css': ['48544D4C207B0D0A0942'],
- 'js': ['696B2E71623D696B2E71'],
- 'rtf': ['7B5C727466315C616E73'],
- 'psd': [''],
- 'eml': ['46726F6D3A203D3F6762'],
- 'wps': ['D0CF11E0A1B11AE10000'],
- 'mdb': ['5374616E64617264204A'],
- 'ps': '[252150532D41646F6265]',
- 'pdf': ['255044462D312E'],
- 'rmvb': ['2E524D46000000120001'],
- 'flv': ['464C5601050000000900'],
- 'mp4': ['00000020667479706D70'],
- 'mp3': [''],
- 'mpg': ['000001BA210001000180'],
- 'wmv': ['3026B2758E66CF11A6D9'],
- 'wav': ['52494646E27807005741'],
- 'avi': ['52494646D07D60074156'],
- 'mid': ['4D546864000000060001'],
- 'zip': ['504B0304140000000800', '504B0304140000080800', '504B03040A0000080000'],
- 'rar': ['526172211A0700CF9073'],
- 'ini': ['235468697320636F6E66'],
- 'jar': ['504B03040A0000000000'],
- 'exe': ['4D5A9000030000000400'],
- 'jsp': ['3C25402070616765206C'],
- 'mf': ['4D616E69666573742D56'],
- 'xml': ['3C3F786D6C2076657273'],
- 'sql': ['494E5345525420494E54'],
- 'java': ['7061636B616765207765'],
- 'bat': ['406563686F206F66660D'],
- 'gz': ['1F8B0800000000000000'],
- 'properties': ['6C6F67346A2E726F6F74'],
- 'class': ['CAFEBABE0000002E0041'],
- 'chm': [''],
- 'mxp': [''],
- 'docx': ['504B0304140006000800', '504B03040A0000000000'],
- 'torrent': ['6431303A637265617465'],
- 'mov': ['6D6F6F76'],
- 'wpd': ['FF575043'],
- 'dbx': ['CFAD12FEC5FD746F'],
- 'pst': ['2142444E'],
- 'qdf': ['AC9EBD8F'],
- 'pwl': ['E3828596'],
- 'ram': ['2E7261FD']
- }
- ret = {}
- for k_hex, v_prefix in type_dict.items():
- if k_hex in types:
- ret[k_hex] = v_prefix
- return ret
- # 字节码转16进制字符串
- def bytes2hex(bytes):
- num = len(bytes)
- hexstr = u""
- for i in range(num):
- t = u"%x" % bytes[i]
- if len(t) % 2:
- hexstr += u""
- hexstr += t
- return hexstr.upper()
- # 获取文件类型
- def file_type(filename):
- binfile = open(filename, 'rb') # 必需二制字读取
- tl = typeList(types=["jpg", "zip", "docx"])
- ftype = None
- for type_name, hcode_list in tl.items():
- flag = False
- for hcode in hcode_list:
- numOfBytes = int(len(hcode) / 2) # 需要读多少字节
- binfile.seek(0) # 每次读取都要回到文件头,不然会一直往后读取
- hbytes = struct.unpack_from("B" * numOfBytes, binfile.read(numOfBytes)) # 一个 "B"表示一个字节
- f_hcode = bytes2hex(hbytes) # 如果判断不出来,打印出这个值,往字典增加即可
- # print("上传数据流hex", s_hcode, '=', "代码字典hex", hcode) # 如果判断不出来,打印出这个值,往字典增加即可
- if f_hcode == hcode:
- flag = True
- break
- if flag:
- ftype = type_name
- break
- binfile.close()
- return ftype
- # 获取字节流类型
- def stream_type(stream, types):
- """
- :param stream:流数据
- :param types:需要判断文件类型,格式:["jpg","jpn"]
- :return:
- """
- tl = typeList(types=types)
- ftype = None
- for type_name, hcode_list in tl.items():
- flag = False
- for hcode in hcode_list:
- numOfBytes = int(len(hcode) / 2) # 需要读多少字节
- hbytes = struct.unpack_from("B" * numOfBytes, stream[0:numOfBytes]) # 一个 "B"表示一个字节
- s_hcode = bytes2hex(hbytes)
- # print("上传数据流hex", s_hcode, '=', "代码字典hex", hcode) # 如果判断不出来,打印出这个值,往字典增加即可
- if s_hcode == hcode:
- flag = True
- break
- if flag:
- ftype = type_name
- break
- return ftype
- def stream_split(stream, count=3):
- """
- 主要处理流是分段获取的数据
- :param stream: 块流
- :param count: 取多少段合成来判断类型,默认三段
- :return:
- """
- block_stream = BytesIO()
- temp = 1
- for block in stream:
- block_stream.write(block)
- if temp == count:
- break
- temp += 1
- return block_stream.getvalue()
is_file_type.py
- type_dict字典,根据自己上传的文件,来填写,数据来自互联网。
基于Flask的上传示例
- @index.route('/upload', methods=['GET', 'POST'])
- def upload():
- if request.method == 'GET':
- return render_template('upload.html')
- upload_obj = request.files.get('code_file')
- if not upload_obj:
- return '没有选择文件上传'
- ret = stream_type(stream_split(upload_obj.stream), ["jpg", "png", "pdf"])
- if not ret:
- return '上传失败,文件类型不匹配,类型必须 "jpg" or "png" or "pdf"'
- file_name = upload_obj.filename
- upload_obj.save(os.path.join('files', file_name))
- return '上传文件成功'
upload.html
- {% extends 'layout.html' %}
- {% block content %}
- <h1>上传代码</h1>
- <form action="" method="post" enctype="multipart/form-data">
- <input type="file" name="code_file">
- <input type="submit" value="上传"></input>
- </form>
- {% endblock %}
开始上传文件:
上传不在列表中的文件类型
上传在列表中的文件类型
Python之基于十六进制判断文件类型的更多相关文章
- Python使用filetype精确判断文件类型
Python使用filetype精确判断文件类型 判断文件类型在开发中非常常见的需求,怎样才能准确的判断文件类型呢?首先大家想到的是文件的后缀,但是非常遗憾的是这种方法是非常不靠谱的,因为文件的后缀是 ...
- 【转】python通过文件头判断文件类型
刚刚看到一个好玩的程序,拉过来.原文地址:https://www.ttlsa.com/python/determine-file-type-by-the-file-header/ 侵权删. ===== ...
- Python使用filetype精确判断文件类型 (文件类型获取)
filetype.py Small and dependency free Python package to infer file type and MIME type checking the m ...
- python准确判断文件类型
判断文件类型在开发中非常常见的需求,怎样才能准确的判断文件类型呢?首先大家想到的是文件的后缀,但是非常遗憾的是这种方法是非常不靠谱的,因为文件的后缀是可以随意更改的,而大家都知道后缀在linux系统下 ...
- JavaScript根据文件名判断文件类型
//JavaScript根据文件名判断文件类型 var imgExt = new Array(".png",".jpg",".jpeg",& ...
- 利用PHP取二进制文件头判断文件类型
<?php $files = array('D:\no.jpg', 'D:\no.png','D:\no2.JPEG','D:\no.BMP'); $fileTypes = array( 779 ...
- Linux中用st_mode判断文件类型
Linux中用st_mode判断文件类型 2012-12-11 12:41 14214人阅读 评论(4) 收藏 举报 分类: Linux(8) C/C++(20) 版权声明:本文为博主原创文章, ...
- php 读取文件头判断文件类型的实现代码
php代码实现读取文件头判断文件类型,支持图片.rar.exe等后缀. 例子: <?php $filename = "11.jpg"; //为图片的路径可以用d:/uploa ...
- PHP取二进制文件头快速判断文件类型的实现代码
通过读取文件头信息来识别文件的真实类型. 一般我们都是按照文件扩展名来判断文件类型,但是这个很不靠谱,轻易就通过修改扩展名来躲避了,一般必须要读取文件信息来识别,PHP扩展中提供了类似 exif_im ...
随机推荐
- AKKA文档2.3(java版)—什么是角色
原文:http://doc.akka.io/docs/akka/2.3.5/general/actors.html译者:Vitas 什么是角色? 前面角色系统一节介绍了一群角色如何形成一个层次结构,并 ...
- 用IDEA开发Spring程序
操作步骤 https://www.cnblogs.com/zyx110/p/11023218.html
- Shell初学(八)linux下的ACL
[1]ACL的作用 简单直接解释一下ACL的作用,即把权限的个别化额外添加. 可以解决如下问题~~比如: [1.1]基于用户: 我有10个用户a1-a10,我有一个文件夹/tmp/test,我想给a1 ...
- mysql事件(event)
[小结]简单案例 SET GLOBAL event_scheduler=1delimiter $$ create definer = current_user event `test`.`event_ ...
- HanLP-分类模块的分词器介绍
最近发现一个很勤快的大神在分享他的一些实操经验,看了一些他自己关于hanlp方面的文章,写的挺好的!转载过来分享给大家!以下为分享原文(无意义的内容已经做了删除) 如下图所示,HanLP的分类模块中单 ...
- p1000 A+B问题
题目描述 Description 输入两个整数A和B,输出他们的和 输入描述 Input Description 输入为一行,包含两个整数A,B.数据保证A与B都在2^31-1的范围内 输出描述 Ou ...
- flower 时区设置
celery 搭配flower使用,flower默认使用的是UTC时间,那么如何在flower中使用当前城市的时间呢 我的环境 celery 3.1.25 ,python 3.69 1.在 app设置 ...
- 什么是云数据库RDS PPAS 版
云数据库PPAS版,是阿里云与EnterpriseDB公司合作基于PostgreSQL高度兼容Oracle语法的数据库服务,为用户提供易于操作的迁移工具,兼容范围涵盖:PL/SQL.数据类型.高级函数 ...
- 初入JavaWeb(半成品)
2019-10-21 20:51:03 初次进行Javaweb的开发. 要求: 1登录账号:要求由6到12位字母.数字.下划线组成,只有字母可以开头:(1分) 2登录密码:要求显示“• ”或“*”表示 ...
- Unity VR-播放demo模型后无法移动视角
资源源于:小意思VR 唉..可怜一下自己,这个问题百度google也不知道怎么搜,没搜出来,在群里问出来的. 当时感觉自己Unity有问题..(就是因为自己啥也不会看不懂) 按右键.或者WASD视角都 ...