當前位置: 首頁>>代碼示例>>Python>>正文


Python AbstractType.AbstractType類代碼示例

本文整理匯總了Python中netzob.Common.Models.Types.AbstractType.AbstractType的典型用法代碼示例。如果您正苦於以下問題:Python AbstractType類的具體用法?Python AbstractType怎麽用?Python AbstractType使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


在下文中一共展示了AbstractType類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: encode

    def encode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """Encodes the specified data into an IPAddress object

        :param data: the data to encode into an IPAddress
        :type data: str or raw bytes (BBBB)
        :return: the encoded IPAddress
        """
        if isinstance(data, (str, int)):
            try:
                ip = IPAddress(data)
                if ip is not None and ip.version == 4 and not ip.is_netmask():
                    return ip
            except:
                pass
        try:

            structFormat = ">"
            if endianness == AbstractType.ENDIAN_BIG:
                structFormat = ">"

            if not sign == AbstractType.SIGN_SIGNED:
                structFormat += "bbbb"
            else:
                structFormat += "BBBB"
            quads = map(str, struct.unpack(structFormat, data))
            strIP = string.join(quads, '.')

            ip = IPAddress(strIP)
            if ip is not None and ip.version == 4 and not ip.is_netmask():
                return ip
        except Exception, e:
            raise TypeError("Impossible encode {0} into an IPv4 data ({1})".format(data, e))
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:32,代碼來源:IPv4.py

示例2: decode

    def decode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the specified data in python raw format.

        >>> from netzob.all import *
        >>> ASCII.decode("hello")
        'hello'
        >>> ASCII.decode('\x5a\x6f\x62\x79\x20\x69\x73\x20\x64\x61\x20\x70\x6c\x61\x63\x65\x20\x21')
        'Zoby is da place !'
        >>> ASCII.decode(1021)
        '1021'

        :param data: the data encoded in ASCII which will be decoded in raw
        :type data: the current type
        :keyword unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str

        :return: data encoded in python raw
        :rtype: python raw
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")

        return str(data).encode('utf-8')
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:28,代碼來源:ASCII.py

示例3: encode

    def encode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the python raw data to the ASCII.

        >>> from netzob.all import *
        >>> raw = ASCII.decode("hello zoby!")
        >>> print ASCII.encode(raw)
        hello zoby!

        :param data: the data encoded in python raw which will be encoded in current type
        :type data: python raw
        :keyword unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str

        :return: data encoded in python raw
        :rtype: python raw
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")

        res = ""
        for elt in data:
            ordElt = ord(elt)
            if ordElt >= 0x20 and ordElt <= 0x7e:  # means between ' ' and '~'
                res += elt
            else:
                res += "."

        return res
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:33,代碼來源:ASCII.py

示例4: encode

    def encode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the python raw data to an HexaString

        >>> from netzob.all import *
        >>> import os
        >>> # Generate 4096 random bytes
        >>> randomData = os.urandom(4096)
        >>> # Convert to hexastring
        >>> hex = TypeConverter.convert(randomData, Raw, HexaString)
        >>> print len(hex)
        8192
        >>> # Convert back to byte and verify we didn't lost anything
        >>> raw = TypeConverter.convert(hex, HexaString, Raw)
        >>> print raw == randomData
        True

        :param data: the data encoded in python raw which will be encoded in current type
        :type data: python raw
        :keyword unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str

        :return: data encoded in Hexa String
        :rtype: python str
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")

        return binascii.hexlify(data)
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:33,代碼來源:HexaString.py

示例5: decode

    def decode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the specified data in python raw format.

        >>> from netzob.all import *
        >>> from netzob.Common.Models.Types.BitArray import BitArray
        >>> d = ASCII.decode("hello netzob")
        >>> r = BitArray.encode(d)
        >>> print r.to01()
        011010000110010101101100011011000110111100100000011011100110010101110100011110100110111101100010
        >>> t = BitArray.decode(r)
        >>> print t
        hello netzob


        :param data: the data encoded in BitArray which will be decoded in raw
        :type data: bitarray
        :keyword unitSize: the unit size of the specified data
        :type unitSize: :class:`netzob.Common.Models.Types.UnitSize.UnitSize`
        :keyword endianness: the endianness of the specified data
        :type endianness: :class:`netzob.Common.Models.Types.Endianness.Endianness`
        :keyword sign: the sign of the specified data
        :type sign: :class:`netzob.Common.Models.Types.Sign.Sign`

        :return: data encoded in python raw
        :rtype: python raw
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")
        return data.tobytes()
開發者ID:EastL,項目名稱:netzob,代碼行數:30,代碼來源:BitArray.py

示例6: encode

    def encode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the python raw data to the BitArray.

        >>> from netzob.all import *
        >>> from netzob.Common.Models.Types.BitArray import BitArray
        >>> BitArray.encode(Integer.decode(20))
        bitarray('00010100')

        :param data: the data encoded in python raw which will be encoded in current type
        :type data: python raw
        :keyword unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str

        :return: data encoded in BitArray
        :rtype: :class:`netzob.Common.Models.Types.BitArray.BitArray`
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")

        if endianness == AbstractType.ENDIAN_BIG:
            endian = 'big'
        elif endianness == AbstractType.ENDIAN_LITTLE:
            endian = 'little'
        else:
            raise ValueError("Invalid endianness value")

        b = bitarray(endian=endian)
        b.frombytes(data)
        return b
開發者ID:EastL,項目名稱:netzob,代碼行數:34,代碼來源:BitArray.py

示例7: __init__

    def __init__(self, _type, unitSize=None, endianness=None, sign=None):
        """Creates a new encoding function that will encode
        the data with the specified types and following its attributes. If an attribute
        is not specified (or set to None), it takes its default value defined in :class:`netzob.Common.Models.Types.AbstractType.AbstractType`.

        :parameter _type: the type that will be used to encode
        :type _type: :class:`type`
        :keyword unitSize: the unitsize of the expected result. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness of the expected result. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign of the expected result. Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str
        """
        self.type = _type
        if unitSize is None:
            unitSize = AbstractType.defaultUnitSize()
        self.unitSize = unitSize

        if endianness is None:
            endianness = AbstractType.defaultEndianness()
        self.endianness = endianness

        if sign is None:
            sign = AbstractType.defaultSign()
        self.sign = sign
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:26,代碼來源:TypeEncodingFunction.py

示例8: canParse

    def canParse(self, data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method returns True if data is an ASCII (utf-8)

        >>> from netzob.all import *
        >>> ASCII().canParse(TypeConverter.convert("hello netzob", ASCII, BitArray))
        True

        The ascii table is defined from 0 to 127:
        >>> ASCII().canParse(TypeConverter.convert(128, Integer, BitArray, src_sign=AbstractType.SIGN_UNSIGNED))
        False

        >>> a = ASCII(nbChars=10)
        >>> a.canParse(TypeConverter.convert("hellohello", ASCII, BitArray))
        True
        >>> a.canParse(TypeConverter.convert("hello hello", ASCII, BitArray))
        False

        >>> a = ASCII(nbChars=(2,20))
        >>> a.canParse(TypeConverter.convert("Netzob", ASCII, BitArray))
        True
        >>> a.canParse(TypeConverter.convert("Hello netzob, what's up ?", ASCII, BitArray))
        False

        :param data: the data to check
        :type data: python raw
        :return: True if data can be parsed as an ASCII
        :rtype: bool
        :raise: TypeError if the data is None
        """

        if data is None:
            raise TypeError("data cannot be None")

        if len(data) == 0:
            return False

        # Ascii must be 8 bits modulo length
        if len(data) % 8 != 0:
            return False

        rawData = data.tobytes()

        try:
            rawData.encode('utf-8')
        except:
            return False

        (minChar, maxChar) = self.nbChars
        if minChar is not None:
            if len(rawData) < minChar:
                return False
        if maxChar is not None:
            if len(rawData) > maxChar:
                return False

        return True
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:56,代碼來源:ASCII.py

示例9: decode

    def decode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """This method convert the specified data in python raw format.

        >>> from netzob.all import *
        >>> print Integer.decode(23)
        \x17

        >>> print Integer.decode(-1, sign=AbstractType.SIGN_UNSIGNED)
        Traceback (most recent call last):
        ...
        error: ubyte format requires 0 <= number <= 255

        >>> print Integer.decode(-1, sign=AbstractType.SIGN_SIGNED)
        \xff

        >>> print Integer.decode(2000000000000000)
        Traceback (most recent call last):
        ...
        error: byte format requires -128 <= number <= 127

        >>> print Integer.decode(2000000000000000, unitSize=AbstractType.UNITSIZE_64)
        \x00\x07\x1a\xfdI\x8d\x00\x00

        >>> print Integer.decode(25, unitSize=AbstractType.UNITSIZE_16, endianness=AbstractType.ENDIAN_LITTLE)
        \x19\x00
        >>> print Integer.decode(25, unitSize=AbstractType.UNITSIZE_16, endianness=AbstractType.ENDIAN_BIG)
        \x00\x19

        >>> val = 167749568
        >>> a = Integer.decode(val, unitSize=AbstractType.UNITSIZE_32)
        >>> b = Integer.encode(a, unitSize=AbstractType.UNITSIZE_32)
        >>> b == val
        True


        :param data: the data encoded in Integer which will be decoded in raw
        :type data: the current type
        :keyword unitSize: the unitsize to consider while encoding. Values must be one of AbstractType.UNITSIZE_*
        :type unitSize: str
        :keyword endianness: the endianness to consider while encoding. Values must be AbstractType.ENDIAN_BIG or AbstractType.ENDIAN_LITTLE
        :type endianness: str
        :keyword sign: the sign to consider while encoding Values must be AbstractType.SIGN_SIGNED or AbstractType.SIGN_UNSIGNED
        :type sign: str

        :return: data encoded in python raw
        :rtype: python raw
        :raise: TypeError if parameters are not valid.
        """
        if data is None:
            raise TypeError("data cannot be None")

        f = Integer.computeFormat(unitSize, endianness, sign)

        return struct.pack(f, int(data))
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:54,代碼來源:Integer.py

示例10: canParse

    def canParse(self, data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """Computes if specified data can be parsed as a Timestamp with the predefined constraints.

        >>> from netzob.all import *
        >>> time = Timestamp()
        >>> time.canParse(TypeConverter.convert(1444494130, Integer, BitArray, src_unitSize=AbstractType.UNITSIZE_32))
        True
        >>> # A timestamp is nothing else than 32bits parsed as an unsigned long
        >>> time.canParse(TypeConverter.convert("test", ASCII, BitArray))
        True
        >>> time.canParse(TypeConverter.convert("te", ASCII, BitArray))
        False
        
        However, some constrains over the definition of the Timestamp can be set to restrain the accepted values

        >>> from netzob.all import *
        >>> time = Timestamp(epoch=Timestamp.EPOCH_WINDOWS, unity=Timestamp.UNITY_NANOSECOND, unitSize = AbstractType.UNITSIZE_64)
        >>> # the returned year is < 1900
        >>> time.canParse(TypeConverter.convert("test", ASCII, BitArray))
        False

        """

        if data is None:
            raise TypeError("data cannot be None")
         
        # Timestamp must be 8 bits modulo length
        if len(data) % 8 != 0:
            return False

        if len(data) < int(self.unitSize):
            return False

        try:

            value = TypeConverter.convert(data[:int(self.unitSize)], BitArray, Integer, dst_unitSize=AbstractType.UNITSIZE_32, dst_sign=AbstractType.SIGN_UNSIGNED)

            # convert the value in seconds
            value = value / self.unity

            # add the utc now with the epoch
            timestamp_datetime = self.epoch + timedelta(seconds=value)
            
            # convert obtained datetime to timestamp in seconds 
            result_sec = int( timestamp_datetime.strftime('%s') )
            
            datetime.fromtimestamp(result_sec)
        except Exception:
            return False
        
        return True
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:51,代碼來源:Timestamp.py

示例11: decode

    def decode(data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """Decode the specified IPv4 data into its raw representation.

        >>> from netzob.all import *
        >>> print IPv4.decode("127.0.0.1")
        \x7f\x00\x00\x01

        """

        if data is None:
            raise TypeError("Data cannot be None")
        ip = IPv4()
        if not ip.canParse(data):
            raise TypeError("Data is not a valid IPv4, cannot decode it.")
        ip = IPAddress(data)
        return ip.packed
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:16,代碼來源:IPv4.py

示例12: encode

    def encode(data, unitSize=AbstractType.UNITSIZE_32, endianness=AbstractType.defaultEndianness(), sign=AbstractType.SIGN_UNSIGNED):
        from netzob.Common.Models.Types.Raw import Raw
        from netzob.Common.Models.Types.TypeConverter import TypeConverter
        from netzob.Common.Models.Types.Integer import Integer

        intValue = TypeConverter.convert(data, Raw, Integer, dst_unitSize=AbstractType.UNITSIZE_32, dst_sign=AbstractType.SIGN_UNSIGNED)
        parsedTimestamp = datetime.fromtimestamp(intValue)

        return parsedTimestamp.strftime("%c")        
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:9,代碼來源:Timestamp.py

示例13: __init__

    def __init__(self, value=None, nbBytes=None, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        if value is not None and not isinstance(value, bitarray):
            from netzob.Common.Models.Types.TypeConverter import TypeConverter
            from netzob.Common.Models.Types.BitArray import BitArray
            value = TypeConverter.convert(value, Raw, BitArray)

        nbBits = self._convertNbBytesinNbBits(nbBytes)

        super(Raw, self).__init__(self.__class__.__name__, value, nbBits, unitSize=unitSize, endianness=endianness, sign=sign)
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:9,代碼來源:Raw.py

示例14: canParse

    def canParse(self, data, unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        """For the moment its always true because we consider
        the decimal type to be very similar to the raw type.

        >>> from netzob.all import *

        >>> BitArray().canParse(TypeConverter.convert("hello netzob", ASCII, BitArray))
        True

        >>> b = BitArray(nbBits=8)
        >>> b.canParse(bitarray('01010101'))
        True

        >>> b.canParse(bitarray('010101011'))
        False

        :param data: the data to check
        :type data: python raw
        :return: True if data can be parsed as a BitArray
        :rtype: bool
        :raise: TypeError if the data is None
        """

        if data is None:
            raise TypeError("data cannot be None")

        if not isinstance(data, bitarray):
            raise TypeError("Data should be a python raw ({0}:{1})".format(data, type(data)))

        if len(data) == 0:
            return False

        (nbMinBits, nbMaxBits) = self.size

        nbBitsData = len(data)

        if nbMinBits is not None and nbMinBits > nbBitsData:
            return False
        if nbMaxBits is not None and nbMaxBits < nbBitsData:
            return False

        return True
開發者ID:EastL,項目名稱:netzob,代碼行數:42,代碼來源:BitArray.py

示例15: __init__

    def __init__(self, value=None, nbChars=(None, None), unitSize=AbstractType.defaultUnitSize(), endianness=AbstractType.defaultEndianness(), sign=AbstractType.defaultSign()):
        if value is not None and not isinstance(value, bitarray):
            from netzob.Common.Models.Types.TypeConverter import TypeConverter
            from netzob.Common.Models.Types.BitArray import BitArray
            value = TypeConverter.convert(value, ASCII, BitArray, src_unitSize=unitSize, src_endianness=endianness, src_sign=sign, dst_unitSize=unitSize, dst_endianness=endianness, dst_sign=sign)
        else:
            value = None

        self.nbChars = nbChars
        nbBits = self._convertNbCharsInNbBits(self.nbChars)

        super(ASCII, self).__init__(self.__class__.__name__, value, nbBits, unitSize=unitSize, endianness=endianness, sign=sign)
開發者ID:chubbymaggie,項目名稱:netzob,代碼行數:12,代碼來源:ASCII.py


注:本文中的netzob.Common.Models.Types.AbstractType.AbstractType類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。