monkey/infection_monkey/monkeyfs.py

62 lines
1.4 KiB
Python
Raw Normal View History

from io import BytesIO
import os
__author__ = 'hoffer'
MONKEYFS_PREFIX = 'monkeyfs://'
2015-10-01 20:32:28 +08:00
open_orig = open
2015-11-30 16:56:20 +08:00
class VirtualFile(BytesIO):
2015-11-30 16:56:20 +08:00
_vfs = {} # virtual File-System
2015-11-30 16:56:20 +08:00
def __init__(self, name, mode='r', buffering=None):
if not name.startswith(MONKEYFS_PREFIX):
name = MONKEYFS_PREFIX + name
self.name = name
self._mode = mode
if name in VirtualFile._vfs:
super(VirtualFile, self).__init__(self._vfs[name])
else:
super(VirtualFile, self).__init__('')
def flush(self):
super(VirtualFile, self).flush()
VirtualFile._vfs[self.name] = self.getvalue()
@staticmethod
def getsize(path):
return len(VirtualFile._vfs[path])
@staticmethod
def isfile(path):
return path in VirtualFile._vfs
2015-11-30 16:56:20 +08:00
def getsize(path):
if path.startswith(MONKEYFS_PREFIX):
return VirtualFile.getsize(path)
else:
return os.stat(path).st_size
2015-11-30 16:56:20 +08:00
def isfile(path):
if path.startswith(MONKEYFS_PREFIX):
return VirtualFile.isfile(path)
else:
return os.path.isfile(path)
2015-11-30 16:56:20 +08:00
def virtual_path(name):
return "%s%s" % (MONKEYFS_PREFIX, name)
2015-11-30 16:56:20 +08:00
def open(name, mode='r', buffering=-1):
2015-11-30 16:56:20 +08:00
# use normal open for regular paths, and our "virtual" open for monkeyfs:// paths
if name.startswith(MONKEYFS_PREFIX):
return VirtualFile(name, mode, buffering)
else:
2015-10-01 20:32:28 +08:00
return open_orig(name, mode=mode, buffering=buffering)