当前位置: 首页>>代码示例>>Python>>正文


Python Config.get方法代码示例

本文整理汇总了Python中lib.core.config.Config.get方法的典型用法代码示例。如果您正苦于以下问题:Python Config.get方法的具体用法?Python Config.get怎么用?Python Config.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在lib.core.config.Config的用法示例。


在下文中一共展示了Config.get方法的5个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: STAP

# 需要导入模块: from lib.core.config import Config [as 别名]
# 或者: from lib.core.config.Config import get [as 别名]
class STAP(Auxiliary):
    """system-wide syscall trace with stap."""
    priority = -10  # low prio to wrap tightly around the analysis

    def __init__(self):
        self.config = Config(cfg="analysis.conf")
        self.proc = None

    def start(self):
        # helper function locating the stap module
        def has_stap(p):
            only_stap = [fn for fn in os.listdir(p) if fn.startswith("stap_") and fn.endswith(".ko")]
            if only_stap: return os.path.join(p, only_stap[0])
            return False

        path_cfg = self.config.get("analyzer_stap_path", None)
        if path_cfg and os.path.exists(path_cfg):
            path = path_cfg
        elif os.path.exists("/root/.cuckoo") and has_stap("/root/.cuckoo"):
            path = has_stap("/root/.cuckoo")
        else:
            log.warning("Could not find STAP LKM, aborting systemtap analysis.")
            return False

        stap_start = time.time()
        self.proc = subprocess.Popen([
            "staprun", "-vv",
            "-x", str(os.getpid()),
            "-o", "stap.log",
            path,
        ], stderr=subprocess.PIPE)

        while "systemtap_module_init() returned 0" not in self.proc.stderr.readline():
            pass

        stap_stop = time.time()
        log.info("STAP aux module startup took %.2f seconds" % (stap_stop - stap_start))
        return True

    @staticmethod
    def _upload_file(local, remote):
        if os.path.exists(local):
            nf = NetlogFile(remote)
            with open(local, "rb") as f:
                for chunk in f:
                    nf.sock.sendall(chunk)  # dirty direct send, no reconnecting
            nf.close()

    def stop(self):
        try:
            r = self.proc.poll()
            log.debug("stap subprocess retval %r", r)
            self.proc.kill()
        except Exception as e:
            log.warning("Exception killing stap: %s", e)

        self._upload_file("stap.log", "logs/all.stap")
开发者ID:CERT-Polska,项目名称:cuckoo,代码行数:59,代码来源:stap.py

示例2: LKM

# 需要导入模块: from lib.core.config import Config [as 别名]
# 或者: from lib.core.config.Config import get [as 别名]
class LKM(Auxiliary):
    """helper LKM for sleep skipping etc"""

    def __init__(self):
        self.config = Config(cfg="analysis.conf")
        self.pids_reported = set()

    def start(self):
        # highest priority: if the vm config specifies the path
        if self.config.get("analyzer_lkm_path", None) and os.path.exists(self.config.get("analyzer_lkm_path")):
            path = self.config.get("analyzer_lkm_path")
        # next: if the analyzer was uploaded with a module for our platform
        elif os.path.exists(os.path.join(platform.machine(), "probelkm.ko")):
            path = os.path.join(platform.machine(), "probelkm.ko")
        # next: default path inside the machine
        elif os.path.exists("/root/.cuckoo/probelkm.ko"):
            path = "/root/.cuckoo/probelkm.ko"
        # next: generic module uploaded with the analyzer (single arch setup maybe?)
        elif os.path.exists("probelkm.ko"):
            path = "probelkm.ko"
        else:
            log.warning("Could not find probelkm :(")
            return False

        os.system("insmod %s trace_descendants=1 target_pid=%u" % (path, os.getpid()))
        return True

    def get_pids(self):
        new = []

        fd = open("/var/log/kern.log")
        for line in fd:
            if not "[probelkm]" in line: continue
            pos1 = line.find("forked to ")
            pos2 = line.find("@", pos1+10)
            if pos1 == -1 or pos2 == -1: continue

            forked_pid = int(line[pos1+10:pos2])

            if forked_pid in self.pids_reported:
                continue

            self.pids_reported.add(forked_pid)
            new.append(forked_pid)

        return new

    def stop(self):
        # i guess we don't need to unload at all
        #os.system("rmmod probelkm")

        # now upload the logfile
        nf = NetlogFile("logs/all.lkm")

        fd = open("/var/log/kern.log")
        for line in fd:
            if not "[probelkm]" in line: continue
            nf.sock.sendall(line) # dirty direct send, no reconnecting

        fd.close()
        nf.close()
开发者ID:Jonnyliu,项目名称:cuckoo,代码行数:63,代码来源:lkm.py

示例3: STAP

# 需要导入模块: from lib.core.config import Config [as 别名]
# 或者: from lib.core.config.Config import get [as 别名]
class STAP(Auxiliary):
    """system-wide syscall trace with stap."""
    priority = -10 # low prio to wrap tightly around the analysis

    def __init__(self):
        self.config = Config(cfg="analysis.conf")
        self.fallback_strace = False

    def start(self):
        # helper function locating the stap module
        def has_stap(p):
            only_stap = [fn for fn in os.listdir(p) if fn.startswith("stap_") and fn.endswith(".ko")]
            if only_stap: return os.path.join(p, only_stap[0])
            return False

        # highest priority: if the vm config specifies the path
        if self.config.get("analyzer_stap_path", None) and os.path.exists(self.config.get("analyzer_stap_path")):
            path = self.config.get("analyzer_lkm_path")
        # next: if a module was uploaded with the analyzer for our platform
        elif os.path.exists(platform.machine()) and has_stap(platform.machine()):
            path = has_stap(platform.machine())
        # next: default path inside the machine
        elif os.path.exists("/root/.cuckoo") and has_stap("/root/.cuckoo"):
            path = has_stap("/root/.cuckoo")
        # next: generic module uploaded with the analyzer (single arch setup maybe?)
        elif has_stap("."):
            path = has_stap(".")
        else:
            # we can't find the stap module, fallback to strace
            log.warning("Could not find STAP LKM, falling back to strace.")
            return self.start_strace()

        stap_start = time.time()
        stderrfd = open("stap.stderr", "wb")
        self.proc = subprocess.Popen(["staprun", "-v", "-x", str(os.getpid()), "-o", "stap.log", path], stderr=stderrfd)

        # read from stderr until the tap script is compiled
        # while True:
        #     if not self.proc.poll() is None:
        #         break
        #     line = self.proc.stderr.readline()
        #     print "DBG LINE", line
        #     if "Pass 5: starting run." in line:
        #         break

        time.sleep(10)
        stap_stop = time.time()
        log.info("STAP aux module startup took %.2f seconds" % (stap_stop - stap_start))
        return True

    def start_strace(self):
        try: os.mkdir("strace")
        except: pass # don't worry, it exists

        stderrfd = open("strace/strace.stderr", "wb")
        self.proc = subprocess.Popen(["strace", "-ff", "-o", "strace/straced", "-p", str(os.getpid())], stderr=stderrfd)
        self.fallback_strace = True
        return True

    def get_pids(self):
        if self.fallback_strace:
            return [self.proc.pid, ]
        return []

    def stop(self):
        try:
            r = self.proc.poll()
            log.debug("stap subprocess retval %r", r)
            self.proc.kill()
        except Exception as e:
            log.warning("Exception killing stap: %s", e)

        if os.path.exists("stap.log"):
            # now upload the logfile
            nf = NetlogFile("logs/all.stap")

            fd = open("stap.log", "rb")
            for chunk in fd:
                nf.sock.sendall(chunk) # dirty direct send, no reconnecting

            fd.close()
            nf.close()

        # in case we fell back to strace
        if os.path.exists("strace"):
            for fn in os.listdir("strace"):
                # we don't need the logs from the analyzer python process itself
                if fn == "straced.%u" % os.getpid(): continue

                fp = os.path.join("strace", fn)

                # now upload the logfile
                nf = NetlogFile("logs/%s" % fn)

                fd = open(fp, "rb")
                for chunk in fd:
                    nf.sock.sendall(chunk) # dirty direct send, no reconnecting

                fd.close()
                nf.close()
开发者ID:0day29,项目名称:cuckoo,代码行数:102,代码来源:stap.py

示例4: __init__

# 需要导入模块: from lib.core.config import Config [as 别名]
# 或者: from lib.core.config.Config import get [as 别名]
class Analyzer:
    """Cuckoo Linux Analyzer.

    This class handles the initialization and execution of the analysis
    procedure, including the auxiliary modules and the analysis packages.
    """

    def __init__(self):
        self.config = None
        self.target = None

    def prepare(self):
        """Prepare env for analysis."""

        # Create the folders used for storing the results.
        create_folders()

        # Initialize logging.
        init_logging()

        # Parse the analysis configuration file generated by the agent.
        self.config = Config(cfg="analysis.conf")

        if self.config.get("clock", None):
            # Set virtual machine clock.
            clock = datetime.datetime.strptime(self.config.clock, "%Y%m%dT%H:%M:%S")
            # Setting date and time.
            os.system("date -s \"{0}\"".format(clock.strftime("%y-%m-%d %H:%M:%S")))

        # We update the target according to its category. If it's a file, then
        # we store the path.
        if self.config.category == "file":
            self.target = os.path.join(tempfile.gettempdir(), self.config.file_name)
        # If it's a URL, well.. we store the URL.
        else:
            self.target = self.config.target

    def complete(self):
        """End analysis."""
        # Dump all the notified files.
        dump_files()

        # Hell yeah.
        log.info("Analysis completed.")

    def run(self):
        """Run analysis.
        @return: operation status.
        """
        self.prepare()

        log.debug("Starting analyzer from: %s", os.getcwd())
        log.debug("Storing results at: %s", PATHS["root"])

        # If no analysis package was specified at submission, we try to select
        # one automatically.
        if not self.config.package:
            log.debug("No analysis package specified, trying to detect "
                      "it automagically.")

            if self.config.category == "file":
                package = "generic"
            else:
                package = "wget"

            # If we weren't able to automatically determine the proper package,
            # we need to abort the analysis.
            if not package:
                raise CuckooError("No valid package available for file "
                                  "type: {0}".format(self.config.file_type))

            log.info("Automatically selected analysis package \"%s\"", package)
        # Otherwise just select the specified package.
        else:
            package = self.config.package

        # Generate the package path.
        package_name = "modules.packages.%s" % package

        # Try to import the analysis package.
        try:
            __import__(package_name, globals(), locals(), ["dummy"], -1)
        # If it fails, we need to abort the analysis.
        except ImportError:
            raise CuckooError("Unable to import package \"{0}\", does "
                              "not exist.".format(package_name))

        # Initialize the package parent abstract.
        Package()

        # Enumerate the abstract subclasses.
        try:
            package_class = Package.__subclasses__()[0]
        except IndexError as e:
            raise CuckooError("Unable to select package class "
                              "(package={0}): {1}".format(package_name, e))

        # Initialize the analysis package.
        pack = package_class(self.config.get_options())

#.........这里部分代码省略.........
开发者ID:CERT-Polska,项目名称:cuckoo,代码行数:103,代码来源:analyzer.py

示例5: Analyzer

# 需要导入模块: from lib.core.config import Config [as 别名]
# 或者: from lib.core.config.Config import get [as 别名]
class Analyzer(object):
    """Cuckoo Linux Analyzer.

    This class handles the initialization and execution of the analysis
    procedure.
    """

    def __init__(self):
        self.pserver = None
        self.config = None
        self.target = None

    def prepare(self):
        """Prepare env for analysis."""

        # Create the folders used for storing the results.
        create_folders()

        # Initialize logging.
        init_logging()

        # Parse the analysis configuration file generated by the agent.
        self.config = Config(cfg="analysis.conf")

        if self.config.get("clock", None):
            # Set virtual machine clock.
            clock = datetime.strptime(self.config.clock, "%Y%m%dT%H:%M:%S")
            # Setting date and time.
            os.system("date -s \"{0}\"".format(clock.strftime("%y-%m-%d %H:%M:%S")))

        # Initialize and start the Pipe Server. This is going to be used for
        # communicating with the injected and monitored processes.
        self.pserver = PipeServer()
        self.pserver.start()

        # We update the target according to its category. If it's a file, then
        # we store the path.
        if self.config.category == "file":
            self.target = os.path.join(gettempdir(), str(self.config.file_name))
            
        # If it's a URL, well.. we store the URL.
        else:
            self.target = self.config.target
    
    def complete(self):
        """End analysis."""
        # Dump all the notified files
        dump_files()
        
        # We're done!
        log.info("Analysis completed.")
        
    def run(self):
        """Run analysis.
        @return: operation status.
        """
        self.prepare()

        log.debug("Starting analyzer from: %s", os.getcwd())
        log.debug("Storing results at: %s", PATHS["root"])
        log.debug("Target is: %s", self.target)

        # If the analysis target is a file, we choose the package according
            # to the file format.
        if self.config.category == "file":
            if ".bash" in self.config.file_name:
                arguments = ["/bin/bash", self.target]
            elif ".sh" in self.config.file_name:
                arguments = ["/bin/sh", self.target]
            elif ".pl" in self.config.file_name:
                arguments = ["/bin/perl", self.target]
            else:
                arguments = [self.target, '']
                os.system("chmod +x " + str(self.target))
                
            if self.config.options:
                if len(arguments) < 2:
                    arguments.pop()
                arguments.append(self.config.options)
        else:
            raise CuckooError("No browser support yet")
        
        # Start file system tracer thread
        fstrace = FilesystemTracer()
        fstrace.start()
        
        # Start system call tracer thread
        proctrace = SyscallTracer(arguments)
        proctrace.start()
        
        if self.config.enforce_timeout:
            log.info("Enabled timeout enforce, running for the full timeout.")
            
        time_counter = 0
        
        while True:
            time_counter += 1
            if time_counter == int(self.config.timeout):
                log.info("Analysis timeout hit, terminating analysis.")
                break
#.........这里部分代码省略.........
开发者ID:0x71,项目名称:cuckoo,代码行数:103,代码来源:analyzer2.py


注:本文中的lib.core.config.Config.get方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。