本文整理汇总了Python中magic.Magic方法的典型用法代码示例。如果您正苦于以下问题:Python magic.Magic方法的具体用法?Python magic.Magic怎么用?Python magic.Magic使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类magic
的用法示例。
在下文中一共展示了magic.Magic方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: magic
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def magic(indata, mime=False):
"""
Performs file magic while maintaining compatibility with different
libraries.
"""
try:
if mime:
mymagic = magic.open(magic.MAGIC_MIME_TYPE)
else:
mymagic = magic.open(magic.MAGIC_NONE)
mymagic.load()
except AttributeError:
mymagic = magic.Magic(mime)
mymagic.file = mymagic.from_file
return mymagic.file(indata)
示例2: get_filetype
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
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 ''
示例3: _try_magic
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def _try_magic(self):
try:
import magic
import weakref
except ImportError:
self._magic = None
else:
try:
_magic = magic.Magic(flags=magic.MAGIC_MIME_TYPE)
def cleanup(x):
_magic.close()
self._magic_weakref = weakref.ref(self, cleanup)
self._magic = _magic
except TypeError:
self._magic = None
except AttributeError:
self._magic = None
示例4: unzip_content
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def unzip_content(r, *args, **kwargs):
content = r.content
with magic.Magic(flags=magic.MAGIC_MIME_TYPE) as m:
mime = m.id_buffer(content)
if mime == "application/zip":
zip_buffer = io.BytesIO(content)
with zipfile.ZipFile(zip_buffer) as zf:
fn = zf.namelist()[0]
with zf.open(fn) as f:
r._content = f.read()
elif mime == "application/x-gzip":
gz_buffer = io.BytesIO(content)
with gzip.GzipFile(fileobj=gz_buffer) as gz:
r._content = gz.read()
else:
r._content = content
return r
示例5: on_file_modified_captured
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def on_file_modified_captured(self, pathname):
if os.path.exists(pathname) and common.is_linux():
import magic
with magic.Magic() as m:
kind = m.id_filename(pathname)
if kind:
pattern = re.compile(r"^(ELF|PE)\S+")
m = pattern.search(kind)
if m is None:
return
else:
return
result = KCybertek().detect_file_sha256(pathname)
if result:
KUEBA_event().on_malware_detect(pathname, result)
示例6: get_decompressed_fileobj
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def get_decompressed_fileobj(fileobj):
"""
Constructs a suitable DecompressorFileProxy for fileobj by parsing the
compression method out of the extension found in filename.
@arg fileobj File-like object to use as input
@return DecompressorFileProxy instance
"""
available_decompressors = {
'application/x-gzip': GZDecompressorFileProxy,
'application/x-bzip2': BZ2DecompressorFileProxy
}
m = magic.Magic(mime=True)
buf = fileobj.read(100)
fileobj = ChainFile(io.StringIO(buf), fileobj)
try:
return available_decompressors[m.from_buffer(buf)](fileobj)
except KeyError as e:
logger.warning("Could not find compressor for [%s], returning "
"original fileobj", e.args[0])
return fileobj
示例7: convert_to_base64
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def convert_to_base64(self, path, is_thumbnail=False):
"""
:param path: file path
:return: returns the converted string and formatted for the send media function send_media
"""
mime = magic.Magic(mime=True)
content_type = mime.from_file(path)
archive = ""
if is_thumbnail:
path = self._resize_image(path, f"{path}.bkp")
with open(path, "rb") as image_file:
archive = b64encode(image_file.read())
archive = archive.decode("utf-8")
if is_thumbnail:
return archive
return "data:" + content_type + ";base64," + archive
示例8: __init__
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def __init__(self, host, port, user, password, threshold=40, secure=False, filepath=None, filename=None, folder_path=None):
"""Connects to neo4j database, loads options and set connectors.
@raise CuckooReportError: if unable to connect.
"""
self.threshold = int(threshold)
self.graph = Graph(host=host, user=user, password=password, secure=secure, port=port)
self.filepath = filepath
self.filename = filename
self.folder_path = folder_path
self.scout = ApiScout()
self.scout.setBaseAddress(0)
self.scout.loadWinApi1024(os.path.abspath(os.path.join(os.path.dirname(__file__))) + os.sep + "data" + os.sep + "winapi1024v1.txt")
self.magictest = magic.Magic(uncompress=True)
CWD = os.path.abspath(os.path.dirname(__file__))
USERDB = os.path.join(CWD, os.path.normpath("data/UserDB.TXT"))
with open(USERDB, 'rt') as f:
sig_data = f.read()
self.signatures = peutils.SignatureDatabase(data=sig_data)
if self.folder_path:
self.files = self.get_files(folder_path)
示例9: handle
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def handle(self, **options):
self.mime_type_magic = magic.Magic(mime=True)
self.gb_parties = PartySet.objects.get(slug='gb')
self.ni_parties = PartySet.objects.get(slug='ni')
start = 0
per_page = 50
url = 'http://pefonline.electoralcommission.org.uk/api/search/Registrations'
params = {
'rows': per_page,
'et': ["pp", "ppm"],
'register': ["gb", "ni"],
'regStatus': ["registered", "deregistered", "lapsed"],
}
with transaction.atomic():
total = None
while total is None or start <= total:
params['start'] = start
resp = requests.get(url + '?' + urlencode(params, doseq=True)).json()
if total is None:
total = resp['Total']
self.parse_data(resp['Result'])
start += per_page
示例10: scan
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def scan(filelist, conf=DEFAULTCONF):
if conf['magicfile']:
try:
maaagic = magic.Magic(magic_file=conf['magicfile'])
except Exception as e:
# TODO: log exception
print("ERROR: Failed to use magic file", conf['magicfile'])
maaagic = magic.Magic()
else:
maaagic = magic.Magic()
results = []
for fname in filelist:
result = maaagic.from_file(fname)
if not isinstance(result, str):
result = result.decode('UTF-8', 'replace')
results.append((fname, result))
metadata = {}
metadata["Name"] = NAME
metadata["Type"] = TYPE
metadata["Include"] = False
return (results, metadata)
示例11: __init__
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def __init__(self):
if AUTODETECT:
if sys.platform.startswith('linux'):
# use the system wide installed version comming with windows, the included magic.mgc might be incompatible
magic_db = os.path.join('/usr/share/file', 'magic.mgc')
else:
magic_db = os.path.join(BASEDIR, '_lib', 'magic', 'db', 'magic.mgc')
if not os.path.exists(magic_db):
raise ImportError('Please install libmagic.')
self.magic = magic.Magic(magic_file=magic_db, mime_encoding=True)
else:
self.magic = False
示例12: filetype
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def filetype(fpath):
try:
mc = magic.Magic()
ftype = mc.from_file(fpath)
except:
ftype = ''
return ftype
示例13: get
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def get(self, notebook_name, note_name):
notebook_name = self.encode_name(notebook_name)
note_name = self.encode_name(note_name)
action = self.get_argument('a', 'view')
if action == 'delete':
self._delete(notebook_name, note_name, confirmed=False)
elif action == 'edit':
self._edit(notebook_name, note_name, confirmed=False)
elif action == 'star':
self._star(notebook_name, note_name, star='set')
elif action == 'unstar':
self._star(notebook_name, note_name, star='unset')
else:
path = join(self.settings.repo, notebook_name, note_name)
dot_path = join(self.settings.repo, notebook_name, '.' + note_name)
highlight = self.get_argument('hl', None)
with Magic() as m:
# Open the file since m.id_filename() does not accept utf8
# paths, not even when using path.decode('utf8')
with open(path) as f:
mime = m.id_buffer(f.read())
if 'text' in mime or 'empty' in mime:
self._view_plaintext(notebook_name=notebook_name,
note_name=note_name,
highlight=highlight)
elif exists(dot_path):
download = self.get_argument('dl', False)
if download:
self._view_file(notebook_name=notebook_name,
note_name=note_name)
else:
self._view_plaintext(notebook_name=notebook_name,
note_name=note_name,
highlight=highlight, dot=True)
else:
self._view_file(notebook_name=notebook_name,
note_name=note_name)
示例14: get_files_types
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def get_files_types(self):
"""
Return the files inside the APK with their types (by using python-magic)
"""
try:
import magic
except ImportError:
return {}
l = {}
builtin_magic = 0
try:
getattr(magic, "Magic")
except AttributeError:
builtin_magic = 1
if builtin_magic:
ms = magic.open(magic.MAGIC_NONE)
ms.load()
for i in self.get_files():
l[ i ] = ms.buffer(self.zip.read(i))
else:
m = magic.Magic()
for i in self.get_files():
l[ i ] = m.from_buffer(self.zip.read(i))
return l
示例15: __init__
# 需要导入模块: import magic [as 别名]
# 或者: from magic import Magic [as 别名]
def __init__(self):
magic.Magic.__init__(self, mime=True, mime_encoding=False, keep_going=True)