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


Python conf.interactive方法代码示例

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


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

示例1: _read_config_file

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def _read_config_file(cf, _globals=globals(), _locals=locals(),
                      interactive=True):
    # type: (str, Dict[str, Any], Dict[str, Any], bool) -> None
    """Read a config file: execute a python file while loading scapy, that
    may contain some pre-configured values.

    If _globals or _locals are specified, they will be updated with
    the loaded vars.  This allows an external program to use the
    function. Otherwise, vars are only available from inside the scapy
    console.

    params:
    - _globals: the globals() vars
    - _locals: the locals() vars
    - interactive: specified whether or not errors should be printed
    using the scapy console or raised.

    ex, content of a config.py file:
        'conf.verb = 42\n'
    Manual loading:
        >>> _read_config_file("./config.py"))
        >>> conf.verb
        42

    """
    log_loading.debug("Loading config file [%s]", cf)
    try:
        with open(cf) as cfgf:
            exec(
                compile(cfgf.read(), cf, 'exec'),
                _globals, _locals
            )
    except IOError as e:
        if interactive:
            raise
        log_loading.warning("Cannot read config file [%s] [%s]", cf, e)
    except Exception:
        if interactive:
            raise
        log_loading.exception("Error during evaluation of config file [%s]",
                              cf) 
开发者ID:secdev,项目名称:scapy,代码行数:43,代码来源:main.py

示例2: restart

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def restart():
    """Restarts scapy"""
    if not conf.interactive or not os.path.isfile(sys.argv[0]):
        raise OSError("Scapy was not started from console")
    if WINDOWS:
        try:
            res_code = subprocess.call([sys.executable] + sys.argv)
        except KeyboardInterrupt:
            res_code = 1
        finally:
            os._exit(res_code)
    os.execv(sys.executable, [sys.executable] + sys.argv) 
开发者ID:secdev,项目名称:scapy,代码行数:14,代码来源:utils.py

示例3: wrpcap

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def wrpcap(filename, pkt, *args, **kargs):
    """Write a list of packets to a pcap file

    :param filename: the name of the file to write packets to, or an open,
        writable file-like object. The file descriptor will be
        closed at the end of the call, so do not use an object you
        do not want to close (e.g., running wrpcap(sys.stdout, [])
        in interactive mode will crash Scapy).
    :param gz: set to 1 to save a gzipped capture
    :param linktype: force linktype value
    :param endianness: "<" or ">", force endianness
    :param sync: do not bufferize writes to the capture file
    """
    with PcapWriter(filename, *args, **kargs) as fdesc:
        fdesc.write(pkt) 
开发者ID:secdev,项目名称:scapy,代码行数:17,代码来源:utils.py

示例4: _pcap_check

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def _pcap_check(cls):
        """Performs checks/restart pcap adapter"""
        if not conf.use_pcap:
            # Winpcap/Npcap isn't installed
            return

        _detect = pcap_service_status()

        def _ask_user():
            if not conf.interactive:
                return False
            msg = "Do you want to start it ? (yes/no) [y]: "
            try:
                # Better IPython compatibility
                import IPython
                return IPython.utils.io.ask_yes_no(msg, default='y')
            except (NameError, ImportError):
                while True:
                    _confir = input(msg)
                    _confir = _confir.lower().strip()
                    if _confir in ["yes", "y", ""]:
                        return True
                    elif _confir in ["no", "n"]:
                        return False
        if _detect:
            # No action needed
            return
        else:
            warning(
                "Scapy has detected that your pcap service is not running !"
            )
            if not conf.interactive or _ask_user():
                succeed = pcap_service_start(askadmin=conf.interactive)
                if succeed:
                    log_loading.info("Pcap service started !")
                    return
        warning("Could not start the pcap service ! "
                "You probably won't be able to send packets. "
                "Deactivating unneeded interfaces and restarting "
                "Scapy might help. Check your winpcap/npcap installation "
                "and access rights.") 
开发者ID:secdev,项目名称:scapy,代码行数:43,代码来源:__init__.py

示例5: _windows_title

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def _windows_title(title=None):
    """Updates the terminal title with the default one or with `title`
    if provided."""
    if conf.interactive:
        _winapi_SetConsoleTitle(title or "Scapy v{}".format(conf.version)) 
开发者ID:secdev,项目名称:scapy,代码行数:7,代码来源:structures.py

示例6: _parse_tcpreplay_result

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def _parse_tcpreplay_result(stdout, stderr, argv):
    """
    Parse the output of tcpreplay and modify the results_dict to populate output information.  # noqa: E501
    Tested with tcpreplay v3.4.4
    Tested with tcpreplay v4.1.2
    :param stdout: stdout of tcpreplay subprocess call
    :param stderr: stderr of tcpreplay subprocess call
    :param argv: the command used in the subprocess call
    :return: dictionary containing the results
    """
    try:
        results = {}
        stdout = plain_str(stdout).lower()
        stderr = plain_str(stderr).strip().split("\n")
        elements = {
            "actual": (int, int, float),
            "rated": (float, float, float),
            "flows": (int, float, int, int),
            "attempted": (int,),
            "successful": (int,),
            "failed": (int,),
            "truncated": (int,),
            "retried packets (eno": (int,),
            "retried packets (eag": (int,),
        }
        multi = {
            "actual": ("packets", "bytes", "time"),
            "rated": ("bps", "mbps", "pps"),
            "flows": ("flows", "fps", "flow_packets", "non_flow"),
            "retried packets (eno": ("retried_enobufs",),
            "retried packets (eag": ("retried_eagain",),
        }
        float_reg = r"([0-9]*\.[0-9]+|[0-9]+)"
        int_reg = r"([0-9]+)"
        any_reg = r"[^0-9]*"
        r_types = {int: int_reg, float: float_reg}
        for line in stdout.split("\n"):
            line = line.strip()
            for elt, _types in elements.items():
                if line.startswith(elt):
                    regex = any_reg.join([r_types[x] for x in _types])
                    matches = re.search(regex, line)
                    for i, typ in enumerate(_types):
                        name = multi.get(elt, [elt])[i]
                        results[name] = typ(matches.group(i + 1))
        results["command"] = " ".join(argv)
        results["warnings"] = stderr[:-1]
        return results
    except Exception as parse_exception:
        if not conf.interactive:
            raise
        log_runtime.error("Error parsing output: " + str(parse_exception))
        return {} 
开发者ID:secdev,项目名称:scapy,代码行数:55,代码来源:sendrecv.py

示例7: ls

# 需要导入模块: from scapy.config import conf [as 别名]
# 或者: from scapy.config.conf import interactive [as 别名]
def ls(obj=None, case_sensitive=False, verbose=False):
    """List  available layers, or infos on a given layer class or name.

    :param obj: Packet / packet name to use
    :param case_sensitive: if obj is a string, is it case sensitive?
    :param verbose:
    """
    is_string = isinstance(obj, six.string_types)

    if obj is None or is_string:
        tip = False
        if obj is None:
            tip = True
            all_layers = sorted(conf.layers, key=lambda x: x.__name__)
        else:
            pattern = re.compile(obj, 0 if case_sensitive else re.I)
            # We first order by accuracy, then length
            if case_sensitive:
                sorter = lambda x: (x.__name__.index(obj), len(x.__name__))
            else:
                obj = obj.lower()
                sorter = lambda x: (x.__name__.lower().index(obj),
                                    len(x.__name__))
            all_layers = sorted((layer for layer in conf.layers
                                 if (isinstance(layer.__name__, str) and
                                     pattern.search(layer.__name__)) or
                                 (isinstance(layer.name, str) and
                                     pattern.search(layer.name))),
                                key=sorter)
        for layer in all_layers:
            print("%-10s : %s" % (layer.__name__, layer._name))
        if tip and conf.interactive:
            print("\nTIP: You may use explore() to navigate through all "
                  "layers using a clear GUI")
    else:
        try:
            fields = _pkt_ls(obj, verbose=verbose)
            is_pkt = isinstance(obj, Packet)
            # Print
            for fname, cls, clsne, dflt, long_attrs in fields:
                cls = cls.__name__ + " " + clsne
                print("%-10s : %-35s =" % (fname, cls), end=' ')
                if is_pkt:
                    print("%-15r" % (getattr(obj, fname),), end=' ')
                print("(%r)" % (dflt,))
                for attr in long_attrs:
                    print("%-15s%s" % ("", attr))
            # Restart for payload if any
            if is_pkt and not isinstance(obj.payload, NoPayload):
                print("--")
                ls(obj.payload)
        except ValueError:
            print("Not a packet class or name. Type 'ls()' to list packet classes.")  # noqa: E501 
开发者ID:secdev,项目名称:scapy,代码行数:55,代码来源:packet.py


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