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


Python moves.range函数代码示例

本文整理汇总了Python中scapy.modules.six.moves.range函数的典型用法代码示例。如果您正苦于以下问题:Python range函数的具体用法?Python range怎么用?Python range使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


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

示例1: pretty_routes

def pretty_routes(rtlst, header, sortBy=0):
    """Pretty route list, and add header"""
    _l_header = len(header[0])
    _space = "  "
    # Sort correctly
    rtlst.sort(key=lambda x: x[sortBy])
    # Append tag
    rtlst = header + rtlst
    # Detect column's width
    colwidth = [max([len(y) for y in x]) for x in apply(zip, rtlst)]
    # Make text fit in box (if exist)
    # TODO: find a better and more precise way of doing this. That's currently working but very complicated
    width = get_terminal_width()
    if width:
        if sum(colwidth) > width:
            # Needs to be cropped
            _med = (width // _l_header) - (1 if WINDOWS else 0) # Windows has a fat window border
            # Crop biggest until size is correct
            for i in range(1, len(colwidth)): # Should use while, but this is safer
                if (sum(colwidth)+6) <= width:
                    break
                _max = max(colwidth)
                colwidth = [_med if x == _max else x for x in colwidth]
            def _crop(x, width):
                _r = x[:width]
                if _r != x:
                    _r = x[:width-3]
                    return _r + "..."
                return _r
            rtlst = [tuple([_crop(rtlst[j][i], colwidth[i]) for i in range(0, len(rtlst[j]))]) for j in range(0, len(rtlst))]
            # Recalculate column's width
            colwidth = [max([len(y) for y in x]) for x in apply(zip, rtlst)]
    fmt = _space.join(["%%-%ds"%x for x in colwidth])
    rt = "\n".join([fmt % x for x in rtlst])
    return rt
开发者ID:mcpat,项目名称:scapy,代码行数:35,代码来源:utils.py

示例2: in6_getRandomizedIfaceId

def in6_getRandomizedIfaceId(ifaceid, previous=None):
    """
    Implements the interface ID generation algorithm described in RFC 3041.
    The function takes the Modified EUI-64 interface identifier generated
    as described in RFC 4291 and an optional previous history value (the
    first element of the output of this function). If no previous interface
    identifier is provided, a random one is generated. The function returns
    a tuple containing the randomized interface identifier and the history
    value (for possible future use). Input and output values are provided in
    a "printable" format as depicted below.

    ex:
    >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3')
    ('4c61:76ff:f46a:a5f3', 'd006:d540:db11:b092')
    >>> in6_getRandomizedIfaceId('20b:93ff:feeb:2d3',
                                 previous='d006:d540:db11:b092')
    ('fe97:46fe:9871:bd38', 'eeed:d79c:2e3f:62e')
    """

    s = b""
    if previous is None:
        d = b"".join(chb(x) for x in range(256))
        for _ in range(8):
            s += chb(random.choice(d))
        previous = s
    s = inet_pton(socket.AF_INET6, "::" + ifaceid)[8:] + previous
    import hashlib
    s = hashlib.md5(s).digest()
    s1, s2 = s[:8], s[8:]
    s1 = chb(orb(s1[0]) | 0x04) + s1[1:]
    s1 = inet_ntop(socket.AF_INET6, b"\xff" * 8 + s1)[20:]
    s2 = inet_ntop(socket.AF_INET6, b"\xff" * 8 + s2)[20:]
    return (s1, s2)
开发者ID:commial,项目名称:scapy,代码行数:33,代码来源:utils6.py

示例3: diffplot

    def diffplot(self, f, delay=1, lfilter=None, **kargs):
        """diffplot(f, delay=1, lfilter=None)
        Applies a function to couples (l[i],l[i+delay])

        A list of matplotlib.lines.Line2D is returned.
        """

        # Get the list of packets
        if lfilter is None:
            l = [f(self.res[i], self.res[i + 1])
                 for i in range(len(self.res) - delay)]
        else:
            l = [f(self.res[i], self.res[i + 1])
                 for i in range(len(self.res) - delay)
                 if lfilter(self.res[i])]

        # Mimic the default gnuplot output
        if kargs == {}:
            kargs = MATPLOTLIB_DEFAULT_PLOT_KARGS
        lines = plt.plot(l, **kargs)

        # Call show() if matplotlib is not inlined
        if not MATPLOTLIB_INLINED:
            plt.show()

        return lines
开发者ID:plorinquer,项目名称:scapy,代码行数:26,代码来源:plist.py

示例4: RRlist2bitmap

def RRlist2bitmap(lst):
    """
    Encode a list of integers representing Resource Records to a bitmap field
    used in the NSEC Resource Record.
    """
    # RFC 4034, 4.1.2. The Type Bit Maps Field

    import math

    bitmap = ""
    lst = sorted(set(lst))

    lst = [abs(x) for x in lst if x <= 65535]

    # number of window blocks
    max_window_blocks = int(math.ceil(lst[-1] / 256.))
    min_window_blocks = int(math.floor(lst[0] / 256.))
    if min_window_blocks == max_window_blocks:
        max_window_blocks += 1

    for wb in range(min_window_blocks, max_window_blocks+1):
        # First, filter out RR not encoded in the current window block
        # i.e. keep everything between 256*wb <= 256*(wb+1)
        rrlist = sorted(x for x in lst if 256 * wb <= x < 256 * (wb + 1))
        if rrlist == []:
            continue

        # Compute the number of bytes used to store the bitmap
        if rrlist[-1] == 0: # only one element in the list
            bytes_count = 1
        else:
            max = rrlist[-1] - 256*wb
            bytes_count = int(math.ceil(max / 8)) + 1  # use at least 1 byte
        if bytes_count > 32: # Don't encode more than 256 bits / values
            bytes_count = 32

        bitmap += struct.pack("B", wb)
        bitmap += struct.pack("B", bytes_count)

        # Generate the bitmap
	# The idea is to remove out of range Resource Records with these steps
	# 1. rescale to fit into 8 bits
	# 2. x gives the bit position ; compute the corresponding value
	# 3. sum everything
        bitmap += b"".join(
	    struct.pack(
		b"B",
		sum(2 ** (7 - (x - 256 * wb) + (tmp * 8)) for x in rrlist
		if 256 * wb + 8 * tmp <= x < 256 * wb + 8 * tmp + 8),
	    ) for tmp in range(bytes_count)
	)

    return bitmap
开发者ID:mcpat,项目名称:scapy,代码行数:53,代码来源:dns.py

示例5: colgen

def colgen(*lstcol,**kargs):
    """Returns a generator that mixes provided quantities forever
    trans: a function to convert the three arguments into a color. lambda x,y,z:(x,y,z) by default"""
    if len(lstcol) < 2:
        lstcol *= 2
    trans = kargs.get("trans", lambda x,y,z: (x,y,z))
    while True:
        for i in range(len(lstcol)):
            for j in range(len(lstcol)):
                for k in range(len(lstcol)):
                    if i != j or j != k or k != i:
                        yield trans(lstcol[(i+j)%len(lstcol)],lstcol[(j+k)%len(lstcol)],lstcol[(k+i)%len(lstcol)])
开发者ID:mcpat,项目名称:scapy,代码行数:12,代码来源:utils.py

示例6: _fix

 def _fix(self, n=0):
     o = random.choice(self.objlist)
     if issubclass(o, ASN1_INTEGER):
         return o(int(random.gauss(0,1000)))
     elif issubclass(o, ASN1_IPADDRESS):
         z = RandIP()._fix()
         return o(z)
     elif issubclass(o, ASN1_STRING):
         z = int(random.expovariate(0.05)+1)
         return o("".join(random.choice(self.chars) for _ in range(z)))
     elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
         z = int(random.expovariate(0.08)+1)
         return o([self.__class__(objlist=self.objlist)._fix(n + 1)
                   for _ in range(z)])
     return ASN1_INTEGER(int(random.gauss(0,1000)))
开发者ID:dark-lbp,项目名称:scapy,代码行数:15,代码来源:asn1.py

示例7: _fix

 def _fix(self):
     if self.fmt is None:
         return ".".join(str(self.idnum) for _ in range(1 + self.depth))
     else:
         oid = []
         for i in self.fmt:
             if i == "*":
                 oid.append(str(self.idnum))
             elif i == "**":
                 oid += [str(self.idnum) for i in range(1 + self.depth)]
             elif isinstance(i, tuple):
                 oid.append(str(random.randrange(*i)))
             else:
                 oid.append(i)
         return ".".join(oid)
开发者ID:netkey,项目名称:scapy,代码行数:15,代码来源:volatile.py

示例8: find_data

    def find_data(packets):
        """Analyse a packet list to extract data offsets from packets data."""
        # a dictionary to count data offsets (ie != 0x80)
        # It's formatted: {(src, dst): (total, [count for offset in len])}
        heuristic = {}

        # Counts possible data locations
        # 0x80 are mainly IOxS and trailling 0x00s are just padding
        for pkt in packets:
            if PNIORealTime in pkt:
                pdu = bytes(pkt[PNIORealTime])[:-4].rstrip(b"\0")

                if (pkt.src, pkt.dst) not in heuristic:
                    heuristic[(pkt.src, pkt.dst)] = (0, [])

                total, counts = heuristic[(pkt.src, pkt.dst)]

                if len(counts) < len(pdu):
                    counts.extend([0 for _ in range(len(pdu) - len(counts))])

                for i in range(len(pdu)):
                    if orb(pdu[i]) != 0x80:
                        counts[i] += 1

                comm = (pkt.src, pkt.dst)
                heuristic[comm] = (total + 1, counts)

        # Determine data locations
        locations = {}
        for comm in heuristic:
            total, counts = heuristic[comm]
            length = len(counts)
            loc = locations[comm] = []
            start = None
            for i in range(length):
                if counts[i] > total // 2:   # Data if more than half is != 0x80  # noqa: E501
                    if start is None:
                        start = i
                else:
                    if start is not None:
                        loc.append((
                            start - length,
                            PNIORealTimeRawData,
                            {"length": i - start}
                        ))
                        start = None

        return locations
开发者ID:plorinquer,项目名称:scapy,代码行数:48,代码来源:pnio_rtc.py

示例9: _ssl_PRF

def _ssl_PRF(secret, seed, req_len):
    """
    Provides the implementation of SSLv3 PRF function:

     SSLv3-PRF(secret, seed) =
        MD5(secret || SHA-1("A" || secret || seed)) ||
        MD5(secret || SHA-1("BB" || secret || seed)) ||
        MD5(secret || SHA-1("CCC" || secret || seed)) || ...

    req_len should not be more than  26 x 16 = 416.
    """
    if req_len > 416:
        warning("_ssl_PRF() is not expected to provide more than 416 bytes")
        return ""

    d = [b"A", b"B", b"C", b"D", b"E", b"F", b"G", b"H", b"I", b"J", b"K", b"L",  # noqa: E501
         b"M", b"N", b"O", b"P", b"Q", b"R", b"S", b"T", b"U", b"V", b"W", b"X",  # noqa: E501
         b"Y", b"Z"]
    res = b""
    hash_sha1 = _tls_hash_algs["SHA"]()
    hash_md5 = _tls_hash_algs["MD5"]()
    rounds = (req_len + hash_md5.hash_len - 1) // hash_md5.hash_len

    for i in range(rounds):
        label = d[i] * (i + 1)
        tmp = hash_sha1.digest(label + secret + seed)
        res += hash_md5.digest(secret + tmp)

    return res[:req_len]
开发者ID:commial,项目名称:scapy,代码行数:29,代码来源:prf.py

示例10: p0f_correl

def p0f_correl(x, y):
    d = 0
    # wwww can be "*" or "%nn". "Tnn" and "Snn" should work fine with
    # the x[0] == y[0] test.
    d += (x[0] == y[0] or y[0] == "*" or (y[0][0] == "%" and x[0].isdigit() and (int(x[0]) % int(y[0][1:])) == 0))  # noqa: E501
    # ttl
    d += (y[1] >= x[1] and y[1] - x[1] < 32)
    for i in [2, 5]:
        d += (x[i] == y[i] or y[i] == '*')
    # '*' has a special meaning for ss
    d += x[3] == y[3]
    xopt = x[4].split(",")
    yopt = y[4].split(",")
    if len(xopt) == len(yopt):
        same = True
        for i in range(len(xopt)):
            if not (xopt[i] == yopt[i] or
                    (len(yopt[i]) == 2 and len(xopt[i]) > 1 and
                     yopt[i][1] == "*" and xopt[i][0] == yopt[i][0]) or
                    (len(yopt[i]) > 2 and len(xopt[i]) > 1 and
                     yopt[i][1] == "%" and xopt[i][0] == yopt[i][0] and
                     int(xopt[i][1:]) % int(yopt[i][2:]) == 0)):
                same = False
                break
        if same:
            d += len(xopt)
    return d
开发者ID:commial,项目名称:scapy,代码行数:27,代码来源:p0f.py

示例11: obfuscate

def obfuscate(pay, secret, session_id, version, seq):
    '''

    Obfuscation methodology from section 3.7
    https://tools.ietf.org/html/draft-ietf-opsawg-tacacs-06#section-3.7

    '''

    pad = b""
    curr_pad = b""

    # pad length must equal the payload to obfuscate.
    # pad = {MD5_1 [,MD5_2 [ ... ,MD5_n]]}

    while len(pad) < len(pay):

        msg = hashlib.md5()
        msg.update(struct.pack('!I', session_id))
        msg.update(secret.encode())
        msg.update(struct.pack('!BB', version, seq))
        msg.update(curr_pad)
        curr_pad = msg.digest()
        pad += curr_pad

    # Obf/Unobfuscation via XOR operation between plaintext and pad

    return b"".join(chb(orb(pad[i]) ^ orb(pay[i])) for i in range(len(pay)))
开发者ID:plorinquer,项目名称:scapy,代码行数:27,代码来源:tacacs.py

示例12: analyse_one_profisafe_location

    def analyse_one_profisafe_location(location, entropy):
        """Analyse one PNIO RTC data location to find if its a PROFISafe

        :param location: location to analyse, a tuple (start, type, config)
        :param entropy: the entropy of each byte of the packet data
        :returns: the configuration associated with the data
        """
        start, klass, conf = location
        if conf["length"] >= 4:     # Minimal PROFISafe length
            succ_count = 0
            for j in range(start, start + conf["length"]):
                # Limit for a CRC is set to 6 bit of entropy min
                if j in entropy and entropy[j] >= 6:
                    succ_count += 1
                else:
                    succ_count = 0
            # PROFISafe profiles must end with at least 3 bytes of high entropy
            if succ_count >= 3:  # Possible profisafe CRC
                return (
                    start,
                    Profisafe,
                    {"CRC": succ_count, "length": conf["length"]}
                )
        # Not a PROFISafe profile
        return (start, klass, conf)
开发者ID:plorinquer,项目名称:scapy,代码行数:25,代码来源:pnio_rtc.py

示例13: analyse_profisafe

    def analyse_profisafe(packets, locations=None):
        """Analyse a packet list to find possible PROFISafe profils.

        It's based on an heuristical analysis of each payload to try to find
        CRC and control/status byte.

        locations: possible data locations. If not provided, analyse_pn_rt will
        be called beforehand. If not given, it calls in the same time
        analyse_data which update the configuration of the data field"""
        # get data locations and entropy of bytes
        if not locations:
            locations = PNIORealTime.find_data(packets)
        entropies = PNIORealTime.data_entropy(packets, locations)

        # Try to find at least 3 high entropy successive bytes (the CRC)
        for comm in entropies:
            entropy = dict(entropies[comm])  # Convert tuples to key => value

            for i in range(len(locations[comm])):
                # update each location with its value after profisafe analysis
                locations[comm][i] = \
                    PNIORealTime.analyse_one_profisafe_location(
                    locations[comm][i], entropy
                )

        return locations
开发者ID:plorinquer,项目名称:scapy,代码行数:26,代码来源:pnio_rtc.py

示例14: pad

    def pad(self, esp):
        """
        Add the correct amount of padding so that the data to encrypt is
        exactly a multiple of the algorithm's block size.

        Also, make sure that the total ESP packet length is a multiple of 4
        bytes.

        @param esp:    an unencrypted _ESPPlain packet

        @return:    an unencrypted _ESPPlain packet with valid padding
        """
        # 2 extra bytes for padlen and nh
        data_len = len(esp.data) + 2

        # according to the RFC4303, section 2.4. Padding (for Encryption)
        # the size of the ESP payload must be a multiple of 32 bits
        align = _lcm(self.block_size, 4)

        # pad for block size
        esp.padlen = -data_len % align

        # Still according to the RFC, the default value for padding *MUST* be an
        # array of bytes starting from 1 to padlen
        # TODO: Handle padding function according to the encryption algo
        esp.padding = struct.pack("B" * esp.padlen, *range(1, esp.padlen + 1))

        # If the following test fails, it means that this algo does not comply
        # with the RFC
        payload_len = len(esp.iv) + len(esp.data) + len(esp.padding) + 2
        if payload_len % 4 != 0:
            raise ValueError('The size of the ESP data is not aligned to 32 bits after padding.')

        return esp
开发者ID:6WIND,项目名称:scapy,代码行数:34,代码来源:ipsec.py

示例15: attach_filter

def attach_filter(fd, iface, bpf_filter_string):
    """Attach a BPF filter to the BPF file descriptor"""

    # Retrieve the BPF byte code in decimal
    command = "%s -i %s -ddd -s 1600 '%s'" % (conf.prog.tcpdump, iface, bpf_filter_string)
    try:
        f = os.popen(command)
    except OSError as msg:
        raise Scapy_Exception("Failed to execute tcpdump: (%s)" % msg)

    # Convert the byte code to a BPF program structure
    lines = f.readlines()
    if lines == []:
        raise Scapy_Exception("Got an empty BPF filter from tcpdump !")

    # Allocate BPF instructions
    size = int(lines[0])
    bpf_insn_a = bpf_insn * size
    bip = bpf_insn_a()

    # Fill the BPF instruction structures with the byte code
    lines = lines[1:]
    for i in range(len(lines)):
        values = [int(v) for v in lines[i].split()]
        bip[i].code = c_ushort(values[0])
        bip[i].jt = c_ubyte(values[1])
        bip[i].jf = c_ubyte(values[2])
        bip[i].k = c_uint(values[3])

    # Create the BPF program and assign it to the interface
    bp = bpf_program(size, bip)
    ret = LIBC.ioctl(c_int(fd), BIOCSETF, cast(pointer(bp), c_char_p))
    if ret < 0:
        raise Scapy_Exception("Can't attach the BPF filter !")
开发者ID:mcpat,项目名称:scapy,代码行数:34,代码来源:core.py


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