本文整理汇总了Python中olefile.isOleFile方法的典型用法代码示例。如果您正苦于以下问题:Python olefile.isOleFile方法的具体用法?Python olefile.isOleFile怎么用?Python olefile.isOleFile使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类olefile
的用法示例。
在下文中一共展示了olefile.isOleFile方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: is_encrypted
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def is_encrypted(file):
r'''
Test if the file is encrypted.
>>> f = open("tests/inputs/plain.doc", "rb")
>>> file = OfficeFile(f)
>>> is_encrypted(file)
False
'''
# TODO: Validate file
if not olefile.isOleFile(file):
return False
file = OfficeFile(file)
return file.is_encrypted()
示例2: __init__
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def __init__(self, file):
self.format = "ooxml"
file.seek(0) # TODO: Investigate the effect (required for olefile.isOleFile)
# olefile cannot process non password protected ooxml files.
# TODO: this code is duplicate of OfficeFile(). Merge?
if olefile.isOleFile(file):
ole = olefile.OleFileIO(file)
self.file = ole
with self.file.openstream('EncryptionInfo') as stream:
self.type, self.info = _parseinfo(stream)
logger.debug("OOXMLFile.type: {}".format(self.type))
self.secret_key = None
if self.type == 'agile':
# TODO: Support aliases?
self.keyTypes = ('password', 'private_key', 'secret_key')
elif self.type == 'standard':
self.keyTypes = ('password', 'secret_key')
elif self.type == 'extensible':
pass
elif zipfile.is_zipfile(file):
self.file = file
self.type, self.info = None, None
self.secret_key = None
else:
raise Exception("Unsupported file format")
示例3: getZipFiles
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def getZipFiles(self, attachment, filename):
'''
Checks a zip for parseable files and extracts all macros
'''
log.debug("[%d] Found attachment with archive extension - file name: %s" % (self.id, filename))
vba_code_all_modules = ''
file_object = StringIO.StringIO(attachment)
files_in_zip = self.zipwalk(file_object,0,[])
for zip_name, zip_data in files_in_zip:
# checks if it is a file
zip_mem_data = StringIO.StringIO(zip_data)
name, ext = os.path.splitext(zip_name.filename)
# send to the VBA_Parser
# fallback with extensions - maybe removed in future releases
if olefile.isOleFile(zip_mem_data) or ext in EXTENSIONS:
log.info("[%d] File in zip detected! Name: %s - check for VBA" % (self.id, zip_name.filename))
vba_parser = olevba.VBA_Parser(filename=zip_name.filename, data=zip_data)
for (subfilename, stream_path, vba_filename, vba_code) in vba_parser.extract_all_macros():
vba_code_all_modules += vba_code + '\n'
return vba_code_all_modules
示例4: stomp_vba
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def stomp_vba(original_file, stomped_file):
if olefile.isOleFile(original_file):
# Make copy of file to modify.
shutil.copyfile(original_file, stomped_file)
stomp_it(stomped_file)
elif zipfile.is_zipfile(original_file):
# unzip to temporary location
tmpdir = tempfile.TemporaryDirectory(prefix="stomp_")
with zipfile.ZipFile(original_file) as zf:
zf.extractall(tmpdir.name)
# iterate through files, call stomp on any ole file
file_list = [f for f in iglob(tmpdir.name + '/**/*', recursive=True) if os.path.isfile(f)]
for f in file_list:
if olefile.isOleFile(f):
stomp_it(f)
# write the new zip file
os.chdir(Path(stomped_file).resolve().parent)
shutil.make_archive(stomped_file, 'zip', tmpdir.name)
if os.path.exists(stomped_file):
os.remove(stomped_file)
os.rename(stomped_file + '.zip', stomped_file)
# This method originally from Kirk Sayre (@bigmacjpg)
示例5: main
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def main():
args = parser.parse_args()
if args.verbose:
logger.removeHandler(logging.NullHandler())
logging.basicConfig(level=logging.DEBUG, format="%(message)s")
logger.debug("Version: {}".format(__version__))
if args.test_encrypted:
if not is_encrypted(args.infile):
print("{}: not encrypted".format(args.infile.name), file=sys.stderr)
sys.exit(1)
else:
logger.debug("{}: encrypted".format(args.infile.name))
return
if not olefile.isOleFile(args.infile):
raise Exception("Not OLE file")
file = OfficeFile(args.infile)
if args.password:
file.load_key(password=args.password)
else:
password = getpass.getpass()
file.load_key(password=password)
if args.outfile is None:
ifWIN32SetBinary(sys.stdout)
if hasattr(sys.stdout, 'buffer'): # For Python 2
args.outfile = sys.stdout.buffer
else:
args.outfile = sys.stdout
file.decrypt(args.outfile)
示例6: is_valid_msg_file
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def is_valid_msg_file(self):
if not isOleFile(self.msg_file_path) and not os.path.exists(self.msg_file_path):
return False
return True
示例7: match
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def match(cls, file_path, result=None):
if isOleFile(file_path):
return super(OutlookMsgIngestor, cls).match(file_path,
result=result)
return -1
示例8: extract_ole_metadata
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def extract_ole_metadata(self, file_path):
with open(file_path, 'rb') as fh:
if not isOleFile(fh):
return
fh.seek(0)
try:
ole = OleFileIO(fh)
self.extract_olefileio_metadata(ole)
except (RuntimeError, IOError):
# OLE reading can go fully recursive, at which point it's OK
# to just eat this runtime error quietly.
log.warning("Failed to read OLE data: %s", self.result)
except Exception:
log.exception("Failed to read OLE data: %s", self.result)
示例9: OfficeFile
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def OfficeFile(file):
'''Return an office file object based on the format of given file.
Args:
file (:obj:`_io.BufferedReader`): Input file.
Returns:
BaseOfficeFile object.
Examples:
>>> with open("tests/inputs/example_password.docx", "rb") as f:
... officefile = OfficeFile(f)
... officefile.keyTypes
('password', 'private_key', 'secret_key')
Given file handle will not be closed, the file position will most certainly
change.
'''
file.seek(0) # required by isOleFile
if olefile.isOleFile(file):
ole = olefile.OleFileIO(file)
elif zipfile.is_zipfile(file): # Heuristic
from .format.ooxml import OOXMLFile
return OOXMLFile(file)
else:
raise Exception("Unsupported file format")
# TODO: Make format specifiable by option in case of obstruction
# Try this first; see https://github.com/nolze/msoffcrypto-tool/issues/17
if ole.exists('EncryptionInfo'):
from .format.ooxml import OOXMLFile
return OOXMLFile(file)
# MS-DOC: The WordDocument stream MUST be present in the file.
# https://msdn.microsoft.com/en-us/library/dd926131(v=office.12).aspx
elif ole.exists('wordDocument'):
from .format.doc97 import Doc97File
return Doc97File(file)
# MS-XLS: A file MUST contain exactly one Workbook Stream, ...
# https://msdn.microsoft.com/en-us/library/dd911009(v=office.12).aspx
elif ole.exists('Workbook'):
from .format.xls97 import Xls97File
return Xls97File(file)
# MS-PPT: A required stream whose name MUST be "PowerPoint Document".
# https://docs.microsoft.com/en-us/openspecs/office_file_formats/ms-ppt/1fc22d56-28f9-4818-bd45-67c2bf721ccf
elif ole.exists('PowerPoint Document'):
from .format.ppt97 import Ppt97File
return Ppt97File(file)
else:
raise Exception("Unrecognized file format")
示例10: zipwalk
# 需要导入模块: import olefile [as 别名]
# 或者: from olefile import isOleFile [as 别名]
def zipwalk(self, zfilename, count, tmpfiles):
z = ZipFile(zfilename,'r')
# start walk
for info in z.infolist():
# 35
is_encrypted = info.flag_bits & 0x1
if not is_encrypted:
fname = info.filename
data = z.read(fname)
extn = (os.path.splitext(fname)[1]).lower()
# create a random secure temp file
tmp_fs, tmpfpath = tempfile.mkstemp(suffix=extn)
# add tmp filename to list
tmpfiles.append(tmpfpath)
if extn=='.zip' or extn=='.7z':
checkz=False
# use the file descriptor to write to the file
tmpfile = os.fdopen(tmp_fs, "w")
tmpfile.write(data)
# Close the file to avoid the open file exception
tmpfile.close()
if is_zipfile(tmpfpath):
checkz=True
count = count+1
# check each round
if count > MAX_ZIP:
self.deleteFileRecursive(tmpfiles)
tmpfiles = []
raise ToManyZipException("[%d] Too many nested zips found - possible zipbomb!" % self.id)
if checkz and not olefile.isOleFile(data):
try:
# recursive call if nested
for x in self.zipwalk(tmpfpath, count, tmpfiles):
yield x
except Exception:
self.deleteFileRecursive(tmpfiles)
tmpfiles = []
raise
else:
# close filehandler if not used
os.close(tmp_fs)
# return the generator
yield (info, data)
# cleanup tmp
self.deleteFileRecursive(tmpfiles)
tmpfiles = []