工作过程中需要判断文件类型可以用一下两个方法,具体如下:
方法一
利用magic模块
先安装magic模块pip install python-magic
import re
import magic
def get_file_type(file_pwd):
"""
判断文件是否是二进制可执行文件
:param file_pwd:
:return:
"""
flag = False
mime_kw = 'x-executable|x-sharedlib|octet-stream|x-object' ###可执行文件、链接库、动态流、对象
try:
magic_mime = magic.from_file(file_pwd, mime=True)
magic_hit = re.search(mime_kw, magic_mime, re.I)
if magic_hit:
flag = True
except Exception as e:
print(e)
return flag
返回结果为TRUE时文件为二进制文件
方法二
# 判断文件是否是elf文件
def is_ELFfile(filepath):
if not os.path.exists(filepath):
logger.info('file path {} doesnot exits'.format(filepath))
return False
# 文件可能被损坏,捕捉异常
try:
FileStates = os.stat(filepath)
FileMode = FileStates[stat.ST_MODE]
if not stat.S_ISREG(FileMode) or stat.S_ISLNK(FileMode): # 如果文件既不是普通文件也不是链接文件
return False
with open(filepath, 'rb') as f:
header = (bytearray(f.read(4))[1:4]).decode(encoding="utf-8")
# logger.info("header is {}".format(header))
if header in ["ELF"]:
# print header
return True
except UnicodeDecodeError as e:
# logger.info("is_ELFfile UnicodeDecodeError {}".format(filepath))
# logger.info(str(e))
pass
return False