本文整理汇总了Python中struct.calcsize方法的典型用法代码示例。如果您正苦于以下问题:Python struct.calcsize方法的具体用法?Python struct.calcsize怎么用?Python struct.calcsize使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类struct
的用法示例。
在下文中一共展示了struct.calcsize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def run(self):
print("VEDIO server starts...")
self.sock.bind(self.ADDR)
self.sock.listen(1)
conn, addr = self.sock.accept()
print("remote VEDIO client success connected...")
data = "".encode("utf-8")
payload_size = struct.calcsize("L")
cv2.namedWindow('Remote', cv2.WINDOW_AUTOSIZE)
while True:
while len(data) < payload_size:
data += conn.recv(81920)
packed_size = data[:payload_size]
data = data[payload_size:]
msg_size = struct.unpack("L", packed_size)[0]
while len(data) < msg_size:
data += conn.recv(81920)
zframe_data = data[:msg_size]
data = data[msg_size:]
frame_data = zlib.decompress(zframe_data)
frame = pickle.loads(frame_data)
cv2.imshow('Remote', frame)
if cv2.waitKey(1) & 0xFF == 27:
break
示例2: chromeos_offset
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def chromeos_offset(self):
"""Calculate the Chrome OS losetup start offset"""
part_format = '<16s16sQQQ72s'
entries_start, entries_num, entry_size = self.gpt_header() # assuming partition table is GPT
lba_size = config.CHROMEOS_BLOCK_SIZE # assuming LBA size
self.seek_stream(entries_start * lba_size)
if not calcsize(part_format) == entry_size:
log(4, 'Partition table entries are not 128 bytes long')
return 0
for index in range(1, entries_num + 1): # pylint: disable=unused-variable
# Entry: type_guid, unique_guid, first_lba, last_lba, attr_flags, part_name
_, _, first_lba, _, _, part_name = unpack(part_format, self.read_stream(entry_size))
part_name = part_name.decode('utf-16').strip('\x00')
if part_name == 'ROOT-A': # assuming partition name is ROOT-A
offset = first_lba * lba_size
break
if not offset:
log(4, 'Failed to calculate losetup offset.')
return 0
return offset
示例3: peer_creds
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def peer_creds(self):
if self._creds is not False:
return self._creds
# works only for unix sockets
if self.request.family != socket.AF_UNIX:
self._creds = None
return self._creds
# pid_t: signed int32, uid_t/gid_t: unsigned int32
fmt = 'iII'
creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERCRED,
struct.calcsize(fmt))
pid, uid, gid = struct.unpack(fmt, creds)
try:
creds = self.request.getsockopt(socket.SOL_SOCKET, SO_PEERSEC,
SELINUX_CONTEXT_LEN)
context = creds.rstrip(b'\x00').decode('utf-8')
except Exception: # pylint: disable=broad-except
logger.debug("Couldn't retrieve SELinux Context", exc_info=True)
context = None
self._creds = {'pid': pid, 'uid': uid, 'gid': gid, 'context': context}
return self._creds
示例4: read
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def read(self, size_or_format):
if isinstance(size_or_format, (str, unicode, bytes)):
size = struct.calcsize(size_or_format)
fmt = size_or_format
else:
size = size_or_format
fmt = None
if self._size - self._pos < size:
raise BuddyError('Unable to read %lu bytes in block' % size)
data = self._value[self._pos:self._pos + size]
self._pos += size
if fmt is not None:
if isinstance(data, bytearray):
return struct.unpack_from(fmt, bytes(data))
else:
return struct.unpack(fmt, data)
else:
return data
示例5: get_platform
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def get_platform():
bits = struct.calcsize("P") * 8
if sys.platform.startswith("linux"):
return "linux{}".format(bits)
elif sys.platform.startswith("win"):
return "win{}".format(bits)
elif sys.platform.startswith("cygwin"):
return "win{}".format(bits)
elif sys.platform.startswith("darwin"):
return "osx{}".format(bits)
else: # pragma: no cover
return None
# The Linux static builds (https://johnvansickle.com/ffmpeg/) are build
# for Linux kernels 2.6.32 and up (at the time of writing, ffmpeg v4.1).
# This corresponds to CentOS 6. This means we should use manylinux2010 and not
# manylinux1.
# manylinux1: https://www.python.org/dev/peps/pep-0513
# manylinux2010: https://www.python.org/dev/peps/pep-0571
# Platform string -> ffmpeg filename
示例6: decrypt_file
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def decrypt_file(key, filename, chunk_size=24*1024):
output_filename = os.path.splitext(filename)[0]
with open(filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, iv)
with open(output_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunk_size)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
示例7: ParseMemoryRuns
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def ParseMemoryRuns(self):
self.runs = []
result = win32file.DeviceIoControl(
self.fd, INFO_IOCTRL, "", 102400, None)
fmt_string = "Q" * len(self.FIELDS)
self.memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
fmt_string, result)))
self.dtb = self.memory_parameters["CR3"]
self.kdbg = self.memory_parameters["KDBG"]
offset = struct.calcsize(fmt_string)
for x in range(self.memory_parameters["NumberOfRuns"]):
start, length = struct.unpack_from("QQ", result, x * 16 + offset)
self.runs.append((start, length))
示例8: _decode_data
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def _decode_data(self, data):
"""Decode the data according to our type."""
valtype = str(self.Type)
if valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]:
if len(data) != struct.calcsize(self.value_formats[valtype]):
return obj.NoneObject(
"Value data did not match the expected data "
"size for a {0}".format(valtype))
if valtype in ["REG_SZ", "REG_EXPAND_SZ", "REG_LINK"]:
data = data.decode('utf-16-le', "ignore")
elif valtype == "REG_MULTI_SZ":
data = data.decode('utf-16-le', "ignore").split('\0')
elif valtype in ["REG_DWORD", "REG_DWORD_BIG_ENDIAN", "REG_QWORD"]:
data = struct.unpack(self.value_formats[valtype], data)[0]
return data
示例9: ParseMemoryRuns
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def ParseMemoryRuns(self, fhandle):
# Set acquisition mode. If the driver does not support this mode it will
# just fall back to the default.
win32file.DeviceIoControl(
fhandle, CTRL_IOCTRL,
struct.pack("I", PMEM_MODE_PTE), 4, None)
result = win32file.DeviceIoControl(
fhandle, INFO_IOCTRL, b"", 102400, None)
fmt_string = "Q" * len(self.FIELDS)
self.memory_parameters = dict(zip(self.FIELDS, struct.unpack_from(
fmt_string, result)))
offset = struct.calcsize(fmt_string)
for x in range(self.memory_parameters["NumberOfRuns"]):
start, length = struct.unpack_from("QQ", result, x * 16 + offset)
self.add_run(start, start, length, self.fhandle_as)
示例10: LoadFromURN
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def LoadFromURN(self):
map_urn = self.urn.Append("map")
map_idx_urn = self.urn.Append("idx")
# Parse the map out of the map stream. If the stream does not exist yet
# we just start with an empty map.
try:
with self.resolver.AFF4FactoryOpen(map_idx_urn) as map_idx:
self.targets = [rdfvalue.URN(utils.SmartUnicode(x))
for x in map_idx.Read(map_idx.Size()).splitlines()]
with self.resolver.AFF4FactoryOpen(map_urn) as map_stream:
read_length = struct.calcsize(Range.format_str)
while 1:
data = map_stream.Read(read_length)
if not data:
break
range = self.deserializeMapPoint(data)
if range.length > 0:
self.tree.addi(range.map_offset, range.map_end, range)
except IOError:
traceback.print_exc()
pass
示例11: handle_io_in
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def handle_io_in(self, data):
fmt = "IIB20s40sB30s30sBBBhHi"
if len(data) != calcsize(fmt):
return 0
values = unpack(fmt, data)
names=["magic","id","type","genre","detail","dist","link",
"tos","fw","nat","real","score","mflags","uptime"]
icd = incident(origin='dionaea.modules.python.p0f')
for i in range(len(values)):
s = values[i]
if type(s) == bytes:
if s.find(b'\x00'):
s = s[:s.find(b'\x00')]
try:
s = s.decode("ascii")
except UnicodeDecodeError:
logger.warning("Unable to decode p0f information %s=%r", i, s, exc_info=True)
icd.set(names[i], s)
elif type(s) == int:
icd.set(names[i], str(s))
icd.set('con',self.con)
icd.report()
self.close()
return len(data)
示例12: findVolumeGuids
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def findVolumeGuids():
DiskExtent = collections.namedtuple(
'DiskExtent', ['DiskNumber', 'StartingOffset', 'ExtentLength'])
Volume = collections.namedtuple(
'Volume', ['Guid', 'MediaType', 'DosDevice', 'Extents'])
found = []
h, guid = FindFirstVolume()
while h and guid:
#print (guid)
#print (guid, win32file.GetDriveType(guid),
# win32file.QueryDosDevice(guid[4:-1]))
hVolume = win32file.CreateFile(
guid[:-1], win32con.GENERIC_READ,
win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
None, win32con.OPEN_EXISTING, win32con.FILE_ATTRIBUTE_NORMAL, None)
extents = []
driveType = win32file.GetDriveType(guid)
if driveType in [win32con.DRIVE_REMOVABLE, win32con.DRIVE_FIXED]:
x = win32file.DeviceIoControl(
hVolume, winioctlcon.IOCTL_VOLUME_GET_VOLUME_DISK_EXTENTS,
None, 512, None)
instream = io.BytesIO(x)
numRecords = struct.unpack('<q', instream.read(8))[0]
fmt = '<qqq'
sz = struct.calcsize(fmt)
while 1:
b = instream.read(sz)
if len(b) < sz:
break
rec = struct.unpack(fmt, b)
extents.append( DiskExtent(*rec) )
vinfo = Volume(guid, driveType, win32file.QueryDosDevice(guid[4:-1]),
extents)
found.append(vinfo)
guid = FindNextVolume(h)
return found
示例13: readLogFile
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def readLogFile(filename, verbose = True):
f = open(filename, 'rb')
print('Opened'),
print(filename)
keys = f.readline().decode('utf8').rstrip('\n').split(',')
fmt = f.readline().decode('utf8').rstrip('\n')
# The byte number of one record
sz = struct.calcsize(fmt)
# The type number of one record
ncols = len(fmt)
if verbose:
print('Keys:'),
print(keys)
print('Format:'),
print(fmt)
print('Size:'),
print(sz)
print('Columns:'),
print(ncols)
# Read data
wholeFile = f.read()
# split by alignment word
chunks = wholeFile.split(b'\xaa\xbb')
log = list()
for chunk in chunks:
if len(chunk) == sz:
values = struct.unpack(fmt, chunk)
record = list()
for i in range(ncols):
record.append(values[i])
log.append(record)
return log
#clid = p.connect(p.SHARED_MEMORY)
示例14: readLogFile
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def readLogFile(filename, verbose = True):
f = open(filename, 'rb')
print('Opened'),
print(filename)
keys = f.readline().decode('utf8').rstrip('\n').split(',')
fmt = f.readline().decode('utf8').rstrip('\n')
# The byte number of one record
sz = struct.calcsize(fmt)
# The type number of one record
ncols = len(fmt)
if verbose:
print('Keys:'),
print(keys)
print('Format:'),
print(fmt)
print('Size:'),
print(sz)
print('Columns:'),
print(ncols)
# Read data
wholeFile = f.read()
# split by alignment word
chunks = wholeFile.split(b'\xaa\xbb')
print ("num chunks")
print (len(chunks))
log = list()
for chunk in chunks:
if len(chunk) == sz:
values = struct.unpack(fmt, chunk)
record = list()
for i in range(ncols):
record.append(values[i])
log.append(record)
return log
示例15: size
# 需要导入模块: import struct [as 别名]
# 或者: from struct import calcsize [as 别名]
def size(self):
return struct.calcsize(self.format())