當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。