docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Initializes the output module object.
Args:
output_mediator (OutputMediator): output mediator.
Raises:
ValueError: if the file handle is missing. | def __init__(self, output_mediator):
super(SQLite4n6TimeOutputModule, self).__init__(output_mediator)
self._connection = None
self._count = 0
self._cursor = None
self._filename = None | 288,540 |
Query database for unique field types.
Args:
field_name (str): name of the filed to retrieve.
Returns:
dict[str, int]: counts of field types by name. | def _GetDistinctValues(self, field_name):
self._cursor.execute(
'SELECT {0:s}, COUNT({0:s}) FROM log2timeline GROUP BY {0:s}'.format(
field_name))
result = {}
row = self._cursor.fetchone()
while row:
if row[0]:
result[row[0]] = row[1]
row = self._cursor.fetc... | 288,541 |
Writes the body of an event to the output.
Args:
event (EventObject): event. | def WriteEventBody(self, event):
# sqlite seems to support milli seconds precision but that seems
# not to be used by 4n6time
row = self._GetSanitizedEventValues(event)
self._cursor.execute(self._INSERT_QUERY, row)
self._count += 1
# Commit the current transaction every 10000 inserts.
... | 288,545 |
Initializes a filter file.
Args:
path (str): path to a file that contains one or more path filters. | def __init__(self, path):
super(FilterFile, self).__init__()
self._path = path | 288,546 |
Build find specification from a filter file.
Args:
environment_variables (Optional[list[EnvironmentVariableArtifact]]):
environment variables.
Returns:
list[dfvfs.FindSpec]: find specification. | def BuildFindSpecs(self, environment_variables=None):
path_attributes = {}
if environment_variables:
for environment_variable in environment_variables:
attribute_name = environment_variable.name.lower()
attribute_value = environment_variable.value
if not isinstance(attribute_v... | 288,547 |
Retrieves the parser names of specific preset category.
Args:
category (str): parser preset categories.
Returns:
list[str]: parser names in alphabetical order. | def _GetParsersFromPresetCategory(cls, category):
preset_definition = cls._presets.GetPresetByName(category)
if preset_definition is None:
return []
preset_names = cls._presets.GetNames()
parser_names = set()
for element_name in preset_definition.parsers:
if element_name in preset... | 288,549 |
Reduces the parsers and plugins to include and exclude.
If an intersection is found, the parser or plugin is removed from
the inclusion set. If a parser is not in inclusion set there is no need
to have it in the exclusion set.
Args:
includes (dict[str, BaseParser]): included parsers and plugins ... | def _ReduceParserFilters(cls, includes, excludes):
if not includes or not excludes:
return
for parser_name in set(includes).intersection(excludes):
# Check parser and plugin list for exact equivalence.
if includes[parser_name] == excludes[parser_name]:
logger.warning(
... | 288,550 |
Creates a signature scanner for format specifications with signatures.
Args:
specification_store (FormatSpecificationStore): format specifications
with signatures.
Returns:
pysigscan.scanner: signature scanner. | def CreateSignatureScanner(cls, specification_store):
scanner_object = pysigscan.scanner()
for format_specification in specification_store.specifications:
for signature in format_specification.signatures:
pattern_offset = signature.offset
if pattern_offset is None:
signatu... | 288,551 |
Retrieves the parser and parser plugin names.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
list[str]: parser and parser plugin names. | def GetParserAndPluginNames(cls, parser_filter_expression=None):
parser_and_plugin_names = []
for parser_name, parser_class in cls.GetParsers(
parser_filter_expression=parser_filter_expression):
parser_and_plugin_names.append(parser_name)
if parser_class.SupportsPlugins():
for ... | 288,554 |
Retrieves the parser plugins information.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
list[tuple[str, str]]: pairs of parser plugin names and descriptions. | def GetParserPluginsInformation(cls, parser_filter_expression=None):
parser_plugins_information = []
for _, parser_class in cls.GetParsers(
parser_filter_expression=parser_filter_expression):
if parser_class.SupportsPlugins():
for plugin_name, plugin_class in parser_class.GetPlugins()... | 288,555 |
Retrieves a specific parser object by its name.
Args:
parser_name (str): name of the parser.
Returns:
BaseParser: parser object or None. | def GetParserObjectByName(cls, parser_name):
parser_class = cls._parser_classes.get(parser_name, None)
if parser_class:
return parser_class()
return None | 288,556 |
Retrieves the parser objects.
Args:
parser_filter_expression (Optional[str]): parser filter expression,
where None represents all parsers and plugins.
Returns:
dict[str, BaseParser]: parsers per name. | def GetParserObjects(cls, parser_filter_expression=None):
includes, excludes = cls._GetParserFilters(parser_filter_expression)
parser_objects = {}
for parser_name, parser_class in iter(cls._parser_classes.items()):
# If there are no includes all parsers are included by default.
if not incl... | 288,557 |
Registers a parser class.
The parser classes are identified based on their lower case name.
Args:
parser_class (type): parser class (subclass of BaseParser).
Raises:
KeyError: if parser class is already set for the corresponding name. | def RegisterParser(cls, parser_class):
parser_name = parser_class.NAME.lower()
if parser_name in cls._parser_classes:
raise KeyError('Parser class already set for name: {0:s}.'.format(
parser_class.NAME))
cls._parser_classes[parser_name] = parser_class | 288,562 |
Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
security = event_values.get('security', None)
if security:
security... | 288,563 |
Initializes the CLI tool object.
Args:
input_reader (Optional[InputReader]): input reader, where None indicates
that the stdin input reader should be used.
output_writer (Optional[OutputWriter]): output writer, where None
indicates that the stdout output writer should be used. | def __init__(self, input_reader=None, output_writer=None):
super(ImageExportTool, self).__init__(
input_reader=input_reader, output_writer=output_writer)
self._abort = False
self._artifact_definitions_path = None
self._artifact_filters = None
self._artifacts_registry = None
self._cu... | 288,564 |
Calculates a SHA-256 digest of the contents of the file entry.
Args:
file_entry (dfvfs.FileEntry): file entry whose content will be hashed.
data_stream_name (str): name of the data stream whose content is to be
hashed.
Returns:
str: hexadecimal representation of the SHA-256 hash or... | def _CalculateDigestHash(self, file_entry, data_stream_name):
file_object = file_entry.GetFileObject(data_stream_name=data_stream_name)
if not file_object:
return None
try:
file_object.seek(0, os.SEEK_SET)
hasher_object = hashers_manager.HashersManager.GetHasher('sha256')
dat... | 288,565 |
Extracts files.
Args:
source_path_specs (list[dfvfs.PathSpec]): path specifications to extract.
destination_path (str): path where the extracted files should be stored.
output_writer (CLIOutputWriter): output writer.
skip_duplicates (Optional[bool]): True if files with duplicate content
... | def _Extract(
self, source_path_specs, destination_path, output_writer,
skip_duplicates=True):
output_writer.Write('Extracting file entries.\n')
path_spec_generator = self._path_spec_extractor.ExtractPathSpecs(
source_path_specs, resolver_context=self._resolver_context)
for path_sp... | 288,567 |
Extracts a data stream.
Args:
file_entry (dfvfs.FileEntry): file entry containing the data stream.
data_stream_name (str): name of the data stream.
destination_path (str): path where the extracted files should be stored.
output_writer (CLIOutputWriter): output writer.
skip_duplicates ... | def _ExtractDataStream(
self, file_entry, data_stream_name, destination_path, output_writer,
skip_duplicates=True):
if not data_stream_name and not file_entry.IsFile():
return
display_name = path_helper.PathHelper.GetDisplayNameForPathSpec(
file_entry.path_spec)
if skip_dupl... | 288,568 |
Extracts a file entry.
Args:
path_spec (dfvfs.PathSpec): path specification of the source file.
destination_path (str): path where the extracted files should be stored.
output_writer (CLIOutputWriter): output writer.
skip_duplicates (Optional[bool]): True if files with duplicate content
... | def _ExtractFileEntry(
self, path_spec, destination_path, output_writer, skip_duplicates=True):
file_entry = path_spec_resolver.Resolver.OpenFileEntry(path_spec)
if not file_entry:
logger.warning('Unable to open file entry for path spec: {0:s}'.format(
path_spec.comparable))
re... | 288,569 |
Retrieves the file system of the source.
Args:
source_path_spec (dfvfs.PathSpec): source path specification of the file
system.
resolver_context (dfvfs.Context): resolver context.
Returns:
tuple: containing:
dfvfs.FileSystem: file system.
dfvfs.PathSpec: mount poin... | def _GetSourceFileSystem(self, source_path_spec, resolver_context=None):
if not source_path_spec:
raise RuntimeError('Missing source.')
file_system = path_spec_resolver.Resolver.OpenFileSystem(
source_path_spec, resolver_context=resolver_context)
type_indicator = source_path_spec.type_i... | 288,571 |
Parses the extensions string.
Args:
extensions_string (str): comma separated extensions to filter. | def _ParseExtensionsString(self, extensions_string):
if not extensions_string:
return
extensions_string = extensions_string.lower()
extensions = [
extension.strip() for extension in extensions_string.split(',')]
file_entry_filter = file_entry_filters.ExtensionsFileEntryFilter(extensi... | 288,572 |
Parses the name string.
Args:
names_string (str): comma separated filenames to filter. | def _ParseNamesString(self, names_string):
if not names_string:
return
names_string = names_string.lower()
names = [name.strip() for name in names_string.split(',')]
file_entry_filter = file_entry_filters.NamesFileEntryFilter(names)
self._filter_collection.AddFilter(file_entry_filter) | 288,573 |
Parses the filter options.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def _ParseFilterOptions(self, options):
names = ['artifact_filters', 'date_filters', 'filter_file']
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=names)
extensions_string = self.ParseStringOption(options, 'extensions_string')
self._ParseExtensionsString(extension... | 288,574 |
Reads the format specification file.
Args:
path (str): path of the format specification file.
Returns:
FormatSpecificationStore: format specification store. | def _ReadSpecificationFile(self, path):
specification_store = specification.FormatSpecificationStore()
with io.open(
path, 'rt', encoding=self._SPECIFICATION_FILE_ENCODING) as file_object:
for line in file_object.readlines():
line = line.strip()
if not line or line.startswith... | 288,576 |
Writes the contents of the source file entry to a destination file.
Note that this function will overwrite an existing file.
Args:
file_entry (dfvfs.FileEntry): file entry whose content is to be written.
data_stream_name (str): name of the data stream whose content is to be
written.
... | def _WriteFileEntry(self, file_entry, data_stream_name, destination_file):
source_file_object = file_entry.GetFileObject(
data_stream_name=data_stream_name)
if not source_file_object:
return
try:
with open(destination_file, 'wb') as destination_file_object:
source_file_obje... | 288,577 |
Adds the filter options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group. | def AddFilterOptions(self, argument_group):
names = ['artifact_filters', 'date_filters', 'filter_file']
helpers_manager.ArgumentHelperManager.AddCommandLineArguments(
argument_group, names=names)
argument_group.add_argument(
'-x', '--extensions', dest='extensions_string', action='store... | 288,578 |
Parses the options and initializes the front-end.
Args:
options (argparse.Namespace): command line arguments.
Raises:
BadConfigOption: if the options are invalid. | def ParseOptions(self, options):
# The data location is required to list signatures.
helpers_manager.ArgumentHelperManager.ParseOptions(
options, self, names=['data_location'])
# Check the list options first otherwise required options will raise.
signature_identifiers = self.ParseStringOpt... | 288,580 |
Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
restore_point_event_type = event_values.get(
'restore_point_event_typ... | 288,582 |
Converts a binary data value into a floating-point value.
Args:
value (bytes): binary data value containing an ASCII string or None.
Returns:
float: floating-point representation of binary data value or None if
value is not set.
Raises:
ParseError: if the floating-point value ... | def _ConvertValueBinaryDataToFloatingPointValue(self, value):
if not value:
return None
value_length = len(value)
if value_length not in (4, 8):
raise errors.ParseError('Unsupported value data size: {0:d}'.format(
value_length))
if value_length == 4:
floating_point_map... | 288,586 |
Extracts an identifier mapping from a SruDbIdMapTable record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
table_name (str): name of the table the record is stored in.
esedb_record (pyesedb.record): record... | def _ParseIdentifierMappingRecord(
self, parser_mediator, table_name, esedb_record):
record_values = self._GetRecordValues(
parser_mediator, table_name, esedb_record)
identifier = record_values.get('IdIndex', None)
if identifier is None:
parser_mediator.ProduceExtractionWarning(
... | 288,589 |
Extracts identifier mappings from the SruDbIdMapTable table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
esedb_table (pyesedb.table): table.
Returns:
dict[int, str]: mapping of numeric identifiers to... | def _ParseIdentifierMappingsTable(self, parser_mediator, esedb_table):
identifier_mappings = {}
for esedb_record in esedb_table.records:
if parser_mediator.abort:
break
identifier, mapped_value = self._ParseIdentifierMappingRecord(
parser_mediator, esedb_table.name, esedb_re... | 288,590 |
Parses the application resource usage table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCache]): cache, which contains information about
the identifiers stored in the SruDbIdMapT... | def ParseApplicationResourceUsage(
self, parser_mediator, cache=None, database=None, table=None,
**unused_kwargs):
self._ParseGUIDTable(
parser_mediator, cache, database, table,
self._APPLICATION_RESOURCE_USAGE_VALUES_MAP,
SRUMApplicationResourceUsageEventData) | 288,591 |
Parses the network data usage monitor table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCache]): cache, which contains information about
the identifiers stored in the SruDbIdMapT... | def ParseNetworkDataUsage(
self, parser_mediator, cache=None, database=None, table=None,
**unused_kwargs):
self._ParseGUIDTable(
parser_mediator, cache, database, table,
self._NETWORK_DATA_USAGE_VALUES_MAP, SRUMNetworkDataUsageEventData) | 288,592 |
Parses the network connectivity usage monitor table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
cache (Optional[ESEDBCache]): cache, which contains information about
the identifiers stored in the Sru... | def ParseNetworkConnectivityUsage(
self, parser_mediator, cache=None, database=None, table=None,
**unused_kwargs):
# TODO: consider making ConnectStartTime + ConnectedTime an event.
self._ParseGUIDTable(
parser_mediator, cache, database, table,
self._NETWORK_CONNECTIVITY_USAGE_V... | 288,593 |
Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
for subkey in registry_key.GetSubkeys():
values_dict = {}
values_dict['subkey_name'] = subkey.name
vendor_identification = None
product_identification = None
try:
subkey_name_parts = subkey.name.split('&')
... | 288,594 |
Formats a packed IPv6 address as a human readable string.
Args:
packed_ip_address (list[int]): packed IPv6 address.
Returns:
str: human readable IPv6 address. | def _FormatPackedIPv6Address(self, packed_ip_address):
# Note that socket.inet_ntop() is not supported on Windows.
octet_pairs = zip(packed_ip_address[0::2], packed_ip_address[1::2])
octet_pairs = [octet1 << 8 | octet2 for octet1, octet2 in octet_pairs]
# TODO: omit ":0000" from the string.
ret... | 288,596 |
Initializes an event source.
Args:
path_spec (Optional[dfvfs.PathSpec]): path specification. | def __init__(self, path_spec=None):
super(EventSource, self).__init__()
self.data_type = self.DATA_TYPE
self.file_entry_type = None
self.path_spec = path_spec | 288,598 |
Initializes an Elasticsearch output module.
Args:
output_mediator (OutputMediator): mediates interactions between output
modules and other components, such as storage and dfvfs. | def __init__(self, output_mediator):
super(ElasticsearchOutputModule, self).__init__(output_mediator)
self._raw_fields = False | 288,599 |
Set raw (non-analyzed) fields.
This is used for sorting and aggregations in Elasticsearch.
https://www.elastic.co/guide/en/elasticsearch/guide/current/
multi-fields.html
Args:
raw_fields (bool): True if raw (non-analyzed) fields should be added. | def SetRawFields(self, raw_fields):
self._raw_fields = raw_fields
if raw_fields:
logger.debug('Elasticsearch adding raw (non-analyzed) fields.')
else:
logger.debug('Elasticsearch not adding raw (non-analyzed) fields.') | 288,600 |
Initializes an extraction warning.
Args:
message (Optional[str]): warning message.
parser_chain (Optional[str]): parser chain to which the warning applies.
path_spec (Optional[dfvfs.PathSpec]): path specification of the file entry
to which the warning applies. | def __init__(self, message=None, parser_chain=None, path_spec=None):
super(ExtractionWarning, self).__init__()
self.message = message
self.parser_chain = parser_chain
self.path_spec = path_spec | 288,602 |
Searches the plist key hierarchy for keys with matching names.
If a match is found a tuple of the key name and value is added to
the matches list.
Args:
key (dict[str, object]): plist key.
names (list[str]): names of the keys to match.
matches (list[str]): keys with matching names. | def _FindKeys(self, key, names, matches):
for name, subkey in iter(key.items()):
if name in names:
matches.append((name, subkey))
if isinstance(subkey, dict):
self._FindKeys(subkey, names, matches) | 288,603 |
Parses file content (data) for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | def _ParseFileData(self, knowledge_base, file_object):
plist_file = plist.PlistFile()
try:
plist_file.Read(file_object)
except IOError as exception:
raise errors.PreProcessFail(
'Unable to read: {0:s} with error: {1!s}'.format(
self.ARTIFACT_DEFINITION_NAME, except... | 288,604 |
Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key. | def _ParsePlistKeyValue(self, knowledge_base, name, value):
if not knowledge_base.GetHostname():
if name in self._PLIST_KEYS:
hostname_artifact = artifacts.HostnameArtifact(name=value)
knowledge_base.SetHostname(hostname_artifact) | 288,605 |
Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key. | def _ParsePlistKeyValue(self, knowledge_base, name, value):
if not knowledge_base.GetValue('keyboard_layout'):
if name in self._PLIST_KEYS:
if isinstance(value, (list, tuple)):
value = value[0]
_, _, keyboard_layout = value.rpartition('.')
knowledge_base.SetValue('keyb... | 288,606 |
Parses a plist key value.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
name (str): name of the plist key.
value (str): value of the plist key. | def _ParsePlistKeyValue(self, knowledge_base, name, value):
if not knowledge_base.GetValue('operating_system_version'):
if name in self._PLIST_KEYS:
knowledge_base.SetValue('operating_system_version', value) | 288,607 |
Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | def _ParseFileEntry(self, knowledge_base, file_entry):
if not file_entry or not file_entry.link:
raise errors.PreProcessFail(
'Unable to read: {0:s} with error: not a symbolic link'.format(
self.ARTIFACT_DEFINITION_NAME))
_, _, time_zone = file_entry.link.partition('zoneinfo/... | 288,608 |
Retrieves plist keys, defaulting to empty values.
Args:
top_level (plistlib._InternalDict): top level plist object.
keys (set[str]): names of keys that should be returned.
depth (int): depth within the plist, where 1 is top level.
Returns:
dict[str, str]: values of the requested keys. | def _GetKeysDefaultEmpty(self, top_level, keys, depth=1):
keys = set(keys)
match = {}
if depth == 1:
for key in keys:
value = top_level.get(key, None)
if value is not None:
match[key] = value
else:
for _, parsed_key, parsed_value in plist_interface.RecurseKey(... | 288,609 |
Retrieves the root key of a plist file.
Args:
file_entry (dfvfs.FileEntry): file entry of the plist.
Returns:
dict[str, object]: plist root key.
Raises:
errors.PreProcessFail: if the preprocessing fails. | def _GetPlistRootKey(self, file_entry):
file_object = file_entry.GetFileObject()
try:
plist_file = plist.PlistFile()
plist_file.Read(file_object)
except IOError as exception:
location = getattr(file_entry.path_spec, 'location', '')
raise errors.PreProcessFail(
'Unabl... | 288,610 |
Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | def _ParseFileEntry(self, knowledge_base, file_entry):
root_key = self._GetPlistRootKey(file_entry)
if not root_key:
location = getattr(file_entry.path_spec, 'location', '')
raise errors.PreProcessFail((
'Unable to read: {0:s} plist: {1:s} with error: missing root '
'key.').... | 288,611 |
Parses a cookie row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseCookieRow(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
cookie_data = self._GetRowValue(query_hash, row, 'value')
cookie_name = self._GetRowValue(query_hash, row, 'name')
hostname = self._GetRowValue(query_hash, row, 'host')
if hostname.startswith('.')... | 288,613 |
Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key. | def ExtractEvents(self, parser_mediator, registry_key, **kwargs):
values_dict = {}
if registry_key.number_of_values == 0:
values_dict['Value'] = 'No values stored in key.'
else:
for registry_value in registry_key.GetValues():
value_name = registry_value.name or '(default)'
... | 288,617 |
Extracts relevant BT entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
device_cache = match.get('DeviceCache', {})
for device, value in iter(device_cache.items()):
name = value.get('Name', '')
if name:
name = ''.join(('Name:', name))
event_data = plist_event.PlistTimeEventData()
... | 288,618 |
Parses file content (data) for a hostname preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing f... | def _ParseFileData(self, knowledge_base, file_object):
text_file_object = dfvfs_text_file.TextFile(file_object, encoding='utf-8')
if not knowledge_base.GetHostname():
hostname = text_file_object.readline()
hostname = hostname.strip()
if hostname:
hostname_artifact = artifacts.Hos... | 288,619 |
Parses file content (data) for system product preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessi... | def _ParseFileData(self, knowledge_base, file_object):
text_file_object = dfvfs_text_file.TextFile(file_object, encoding='utf-8')
system_product = text_file_object.readline()
system_product = system_product.strip()
if not knowledge_base.GetValue('operating_system_product'):
if system_produc... | 288,620 |
Parses file content (data) for system product preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessi... | def _ParseFileData(self, knowledge_base, file_object):
text_file_object = dfvfs_text_file.TextFile(file_object, encoding='utf-8')
system_product = text_file_object.readline()
# Only parse known default /etc/issue file contents.
if system_product.startswith('Debian GNU/Linux '):
system_produ... | 288,621 |
Parses file content (data) for system product preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessi... | def _ParseFileData(self, knowledge_base, file_object):
text_file_object = dfvfs_text_file.TextFile(file_object, encoding='utf-8')
product_values = {}
for line in text_file_object.readlines():
line = line.strip()
if line.startswith('#'):
continue
key, value = line.split('=')
... | 288,622 |
Parses artifact file system data for a preprocessing attribute.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_entry (dfvfs.FileEntry): file entry that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessing fails. | def _ParseFileEntry(self, knowledge_base, file_entry):
if file_entry.link:
# Determine the timezone based on the file path.
_, _, time_zone = file_entry.link.partition('zoneinfo/')
else:
# Determine the timezone based on the timezone information file.
file_object = file_entry.GetFi... | 288,623 |
Parses file content (data) for user account preprocessing attributes.
Args:
knowledge_base (KnowledgeBase): to fill with preprocessing information.
file_object (dfvfs.FileIO): file-like object that contains the artifact
value data.
Raises:
errors.PreProcessFail: if the preprocessin... | def _ParseFileData(self, knowledge_base, file_object):
line_reader = line_reader_file.BinaryLineReader(file_object)
try:
reader = line_reader_file.BinaryDSVReader(line_reader, b':')
except csv.Error as exception:
raise errors.PreProcessFail(
'Unable to read: {0:s} with error: {1!... | 288,624 |
Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse grou... | def AddArguments(cls, argument_group):
argument_group.add_argument(
'--index_name', dest='index_name', type=str, action='store',
default=cls._DEFAULT_INDEX_NAME, help=(
'Name of the index in ElasticSearch.'))
argument_group.add_argument(
'--doc_type', dest='document_type... | 288,625 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object is of the wrong type.
BadConfigOption: when a configuration parameter fails validation. | def ParseOptions(cls, options, output_module):
elastic_output_modules = (
elastic.ElasticsearchOutputModule, elastic.ElasticsearchOutputModule)
if not isinstance(output_module, elastic_output_modules):
raise errors.BadConfigObject(
'Output module is not an instance of ElasticsearchO... | 288,626 |
Converts a dictionary into a list of strings.
Args:
data_dict (dict[str, object]): dictionary to convert.
Returns:
list[str]: list of strings. | def _DictToListOfStrings(self, data_dict):
ret_list = []
for key, value in iter(data_dict.items()):
if key in ('body', 'datetime', 'type', 'room', 'rooms', 'id'):
continue
ret_list.append('{0:s} = {1!s}'.format(key, value))
return ret_list | 288,628 |
Extracts values from a JQuery string.
Args:
jquery_raw (str): JQuery string.
Returns:
dict[str, str]: extracted values. | def _ExtractJQuery(self, jquery_raw):
data_part = ''
if not jquery_raw:
return {}
if '[' in jquery_raw:
_, _, first_part = jquery_raw.partition('[')
data_part, _, _ = first_part.partition(']')
elif jquery_raw.startswith('//'):
_, _, first_part = jquery_raw.partition('{')
... | 288,629 |
Parses chat comment data.
Args:
data (dict[str, object]): chat comment data as returned by SQLite.
Returns:
dict[str, object]: parsed chat comment data. | def _ParseChatData(self, data):
data_store = {}
if 'body' in data:
body = data.get('body', '').replace('\n', ' ')
if body.startswith('//') and '{' in body:
body_dict = self._ExtractJQuery(body)
title, _, _ = body.partition('{')
body = '{0:s} <{1!s}>'.format(
... | 288,630 |
Parses a single row from the receiver and cache response table.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseReceiverData(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
data = {}
key_url = self._GetRowValue(query_hash, row, 'request_key')
data_dict = {}
description = 'MacKeeper Entry'
# Check the URL, since that contains vital information about the ... | 288,631 |
Deregisters a formatter class.
The formatter classes are identified based on their lower case data type.
Args:
formatter_class (type): class of the formatter.
Raises:
KeyError: if formatter class is not set for the corresponding data type. | def DeregisterFormatter(cls, formatter_class):
formatter_data_type = formatter_class.DATA_TYPE.lower()
if formatter_data_type not in cls._formatter_classes:
raise KeyError(
'Formatter class not set for data type: {0:s}.'.format(
formatter_class.DATA_TYPE))
del cls._format... | 288,632 |
Retrieves the formatter object for a specific data type.
Args:
data_type (str): data type.
Returns:
EventFormatter: corresponding formatter or the default formatter if
not available. | def GetFormatterObject(cls, data_type):
data_type = data_type.lower()
if data_type not in cls._formatter_objects:
formatter_object = None
if data_type in cls._formatter_classes:
formatter_class = cls._formatter_classes[data_type]
# TODO: remove the need to instantiate the Forma... | 288,633 |
Retrieves the formatted message strings for a specific event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions between
formatters and other components, such as storage and Windows EventLog
resources.
event (EventObject): event.
Returns:
list[... | def GetMessageStrings(cls, formatter_mediator, event):
formatter_object = cls.GetFormatterObject(event.data_type)
return formatter_object.GetMessages(formatter_mediator, event) | 288,634 |
Retrieves the formatted source strings for a specific event object.
Args:
event (EventObject): event.
Returns:
list[str, str]: short and long version of the source of the event. | def GetSourceStrings(cls, event):
# TODO: change this to return the long variant first so it is consistent
# with GetMessageStrings.
formatter_object = cls.GetFormatterObject(event.data_type)
return formatter_object.GetSources(event) | 288,635 |
Retrieves all PE section names.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[str]: names of the sections. | def _GetSectionNames(self, pefile_object):
section_names = []
for section in pefile_object.sections:
section_name = getattr(section, 'Name', b'')
# Ensure the name is decoded correctly.
try:
section_name = '{0:s}'.format(section_name.decode('unicode_escape'))
except UnicodeD... | 288,637 |
Retrieves timestamps from the import directory, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: import timestamps. | def _GetImportTimestamps(self, pefile_object):
import_timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_IMPORT'):
return import_timestamps
for importdata in pefile_object.DIRECTORY_ENTRY_IMPORT:
dll_name = getattr(importdata, 'dll', '')
try:
dll_name = dll_name.de... | 288,638 |
Retrieves timestamps from resource directory entries, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
list[int]: resource timestamps. | def _GetResourceTimestamps(self, pefile_object):
timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_RESOURCE'):
return timestamps
for entrydata in pefile_object.DIRECTORY_ENTRY_RESOURCE.entries:
directory = entrydata.directory
timestamp = getattr(directory, 'TimeDateStamp'... | 288,639 |
Retrieves the timestamp from the Load Configuration directory.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
int: load configuration timestamps or None if there are none present. | def _GetLoadConfigTimestamp(self, pefile_object):
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_LOAD_CONFIG'):
return None
timestamp = getattr(
pefile_object.DIRECTORY_ENTRY_LOAD_CONFIG.struct, 'TimeDateStamp', 0)
return timestamp | 288,640 |
Retrieves timestamps from delay import entries, if available.
Args:
pefile_object (pefile.PE): pefile object.
Returns:
tuple[str, int]: name of the DLL being imported and the second is
the timestamp of the entry. | def _GetDelayImportTimestamps(self, pefile_object):
delay_import_timestamps = []
if not hasattr(pefile_object, 'DIRECTORY_ENTRY_DELAY_IMPORT'):
return delay_import_timestamps
for importdata in pefile_object.DIRECTORY_ENTRY_DELAY_IMPORT:
dll_name = importdata.dll
try:
dll_name ... | 288,641 |
Parses a Portable Executable (PE) file-like object.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
file_object (dfvfs.FileIO): a file-like object.
Raises:
UnableToParseFile: when the file cannot be pars... | def ParseFileObject(self, parser_mediator, file_object):
pe_data = file_object.read()
try:
pefile_object = pefile.PE(data=pe_data, fast_load=True)
pefile_object.parse_data_directories(
directories=[
pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_IMPORT'],
pe... | 288,642 |
Iterates over the log lines and provide a reader for the values.
Args:
line_reader (iter): yields each line in the log file.
Yields:
dict[str, str]: column values keyed by column header. | def _CreateDictReader(self, line_reader):
for line in line_reader:
if isinstance(line, py2to3.BYTES_TYPE):
try:
line = codecs.decode(line, self._encoding)
except UnicodeDecodeError as exception:
raise errors.UnableToParseFile(
'Unable decode line with err... | 288,644 |
Parses a line of the log file and produces events.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row_offset (int): line number of the row.
row (dict[str, str]): fields of a single row, as specified in COLUM... | def ParseRow(self, parser_mediator, row_offset, row):
timestamp = self._ParseTimestamp(parser_mediator, row)
if timestamp is None:
return
try:
action = int(row['action'], 10)
except (ValueError, TypeError):
action = None
try:
scan_type = int(row['scan_type'], 10)
e... | 288,647 |
Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified in COLUMNS.
Returns:
bool: True if thi... | def VerifyRow(self, parser_mediator, row):
if len(row) < self.MIN_COLUMNS:
return False
# Check the date format!
# If it doesn't parse, then this isn't a Trend Micro AV log.
try:
timestamp = self._ConvertToTimestamp(row['date'], row['time'])
except (ValueError, TypeError):
re... | 288,648 |
Parses a line of the log file and produces events.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row_offset (int): line number of the row.
row (dict[str, str]): fields of a single row, as specified in COLUM... | def ParseRow(self, parser_mediator, row_offset, row):
timestamp = self._ParseTimestamp(parser_mediator, row)
if timestamp is None:
return
event_data = TrendMicroUrlEventData()
event_data.offset = row_offset
# Convert and store integer values.
for field in (
'credibility_rati... | 288,650 |
Verifies if a line of the file is in the expected format.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, str]): fields of a single row, as specified in COLUMNS.
Returns:
bool: True if thi... | def VerifyRow(self, parser_mediator, row):
if len(row) < self.MIN_COLUMNS:
return False
# Check the date format!
# If it doesn't parse, then this isn't a Trend Micro AV log.
try:
timestamp = self._ConvertToTimestamp(row['date'], row['time'])
except ValueError:
return False
... | 288,651 |
Adds command line arguments the helper supports to an argument group.
This function takes an argument parser or an argument group object and adds
to it all the command line arguments this helper supports.
Args:
argument_group (argparse._ArgumentGroup|argparse.ArgumentParser):
argparse grou... | def AddArguments(cls, argument_group):
argument_group.add_argument(
'--server', dest='server', type=str, action='store',
default=cls._DEFAULT_SERVER, metavar='HOSTNAME',
help='The hostname or server IP address of the server.')
argument_group.add_argument(
'--port', dest='por... | 288,652 |
Parses and validates options.
Args:
options (argparse.Namespace): parser options.
output_module (OutputModule): output module to configure.
Raises:
BadConfigObject: when the output module object does not have the
SetServerInformation method. | def ParseOptions(cls, options, output_module):
if not hasattr(output_module, 'SetServerInformation'):
raise errors.BadConfigObject('Unable to set server information.')
server = cls._ParseStringOption(
options, 'server', default_value=cls._DEFAULT_SERVER)
port = cls._ParseNumericOption(
... | 288,653 |
Initializes a VirusTotal analyzer.
Args:
hash_queue (Queue.queue): queue that contains hashes to be analyzed.
hash_analysis_queue (Queue.queue): queue the analyzer will append
HashAnalysis objects to. | def __init__(self, hash_queue, hash_analysis_queue, **kwargs):
super(VirusTotalAnalyzer, self).__init__(
hash_queue, hash_analysis_queue, **kwargs)
self._api_key = None
self._checked_for_old_python_version = False | 288,654 |
Queries VirusTotal for a specfic hashes.
Args:
digests (list[str]): hashes to look up.
Returns:
dict[str, object]: JSON response or None on error. | def _QueryHashes(self, digests):
url_parameters = {'apikey': self._api_key, 'resource': ', '.join(digests)}
try:
json_response = self.MakeRequestAndDecodeJSON(
self._VIRUSTOTAL_API_REPORT_URL, 'GET', params=url_parameters)
except errors.ConnectionError as exception:
json_response... | 288,655 |
Looks up hashes in VirusTotal using the VirusTotal HTTP API.
The API is documented here:
https://www.virustotal.com/en/documentation/public-api/
Args:
hashes (list[str]): hashes to look up.
Returns:
list[HashAnalysis]: analysis results.
Raises:
RuntimeError: If the VirusTotal... | def Analyze(self, hashes):
if not self._api_key:
raise RuntimeError('No API key specified for VirusTotal lookup.')
hash_analyses = []
json_response = self._QueryHashes(hashes) or []
# VirusTotal returns a dictionary when a single hash is queried
# and a list when multiple hashes are qu... | 288,656 |
Generates a list of strings that will be used in the event tag.
Args:
hash_information (dict[str, object]): the JSON decoded contents of the
result of a VirusTotal lookup, as produced by the VirusTotalAnalyzer.
Returns:
list[str]: strings describing the results from VirusTotal. | def GenerateLabels(self, hash_information):
response_code = hash_information['response_code']
if response_code == self._VIRUSTOTAL_NOT_PRESENT_RESPONSE_CODE:
return ['virustotal_not_present']
if response_code == self._VIRUSTOTAL_PRESENT_RESPONSE_CODE:
positives = hash_information['positive... | 288,658 |
Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
priority_level = event_values.get('level', None)
if isinstance(priority_l... | 288,659 |
Parses a generic windows timeline row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseGenericRow(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = WindowsTimelineGenericEventData()
# Payload is JSON serialized as binary data in a BLOB field, with the text
# encoded as UTF-8.
payload_json_bytes = bytes(self._GetRowValue(q... | 288,662 |
Parses a timeline row that describes a user interacting with an app.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseUserEngagedRow(
self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
event_data = WindowsTimelineUserEngagedEventData()
event_data.package_identifier = self._GetRowValue(
query_hash, row, 'PackageName')
# Payload is JSON serialized as binary data in... | 288,663 |
Parses a Call record row.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
query (str): query that created the row.
row (sqlite3.Row): row. | def ParseCallsRow(self, parser_mediator, query, row, **unused_kwargs):
query_hash = hash(query)
call_type = self._GetRowValue(query_hash, row, 'type')
call_type = self.CALL_TYPE.get(call_type, 'UNKNOWN')
duration = self._GetRowValue(query_hash, row, 'duration')
timestamp = self._GetRowValue(qu... | 288,665 |
Check if it is a valid MacOS system account plist file name.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
plist_name (str): name of the plist.
top_level (dict[str, object]): plist top-level key. | def Process(self, parser_mediator, plist_name, top_level, **kwargs):
super(MacUserPlugin, self).Process(
parser_mediator, plist_name=self.PLIST_PATH, top_level=top_level) | 288,666 |
Extracts relevant user timestamp entries.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
match (Optional[dict[str: object]]): keys extracted from PLIST_KEYS. | def GetEntries(self, parser_mediator, match=None, **unused_kwargs):
if 'name' not in match or 'uid' not in match:
return
account = match['name'][0]
uid = match['uid'][0]
for policy in match.get('passwordpolicyoptions', []):
try:
xml_policy = ElementTree.fromstring(policy)
... | 288,667 |
Determines the formatted message strings for an event object.
Args:
formatter_mediator (FormatterMediator): mediates the interactions
between formatters and other components, such as storage and Windows
EventLog resources.
event (EventObject): event.
Returns:
tuple(str, s... | def GetMessages(self, formatter_mediator, event):
if self.DATA_TYPE != event.data_type:
raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format(
event.data_type))
event_values = event.CopyToDict()
regvalue = event_values.get('regvalue', {})
string_parts = []
for key... | 288,668 |
Determines if a Windows Registry key matches the filter.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
Returns:
bool: True if the Windows Registry key matches the filter. | def Match(self, registry_key):
key_path = registry_key.path.upper()
# Prevent this filter matching non-string MRUList values.
for ignore_key_path_suffix in self._IGNORE_KEY_PATH_SUFFIXES:
if key_path.endswith(ignore_key_path_suffix):
return False
return super(MRUListStringRegistryKey... | 288,669 |
Parses the MRUList value in a given Registry key.
Args:
registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains
the MRUList value.
Returns:
mrulist_entries: MRUList entries or None if not available. | def _ParseMRUListValue(self, registry_key):
mrulist_value = registry_key.GetValueByName('MRUList')
# The key exists but does not contain a value named "MRUList".
if not mrulist_value:
return None
mrulist_entries_map = self._GetDataTypeMap('mrulist_entries')
context = dtfabric_data_maps... | 288,670 |
Extract event objects from a MRUList Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
codepage (Optional[str]): extended ASCII string... | def _ParseMRUListKey(self, parser_mediator, registry_key, codepage='cp1252'):
try:
mrulist = self._ParseMRUListValue(registry_key)
except (ValueError, errors.ParseError) as exception:
parser_mediator.ProduceExtractionWarning(
'unable to parse MRUList value with error: {0!s}'.format(ex... | 288,671 |
Parses the MRUList entry value.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key that contains
the MRUList value.
entry_index (int): MRUL... | def _ParseMRUListEntryValue(
self, parser_mediator, registry_key, entry_index, entry_letter, **kwargs):
value_string = ''
value = registry_key.GetValueByName('{0:s}'.format(entry_letter))
if value is None:
parser_mediator.ProduceExtractionWarning(
'missing MRUList value: {0:s} in... | 288,672 |
Extracts events from a Windows Registry key.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
codepage (Optional[str]): extended ASCII string codep... | def ExtractEvents(
self, parser_mediator, registry_key, codepage='cp1252', **kwargs):
self._ParseMRUListKey(parser_mediator, registry_key, codepage=codepage) | 288,673 |
Initializes a delimiter separated values (DSV) parser.
Args:
encoding (Optional[str]): encoding used in the DSV file, where None
indicates the codepage of the parser mediator should be used. | def __init__(self, encoding=None):
super(DSVParser, self).__init__()
self._encoding = encoding
if py2to3.PY_2:
self._end_of_line = b'\n'
else:
self._end_of_line = '\n'
self._maximum_line_length = (
len(self._end_of_line) +
len(self.COLUMNS) * (self.FIELD_SIZE_LIMIT +... | 288,675 |
Converts all strings in a DSV row dict to Unicode.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
row (dict[str, bytes]): a row from a DSV file, where the dictionary
key contains the column name and the ... | def _ConvertRowToUnicode(self, parser_mediator, row):
for key, value in iter(row.items()):
if isinstance(value, py2to3.UNICODE_TYPE):
continue
try:
row[key] = value.decode(self._encoding)
except UnicodeDecodeError:
replaced_value = value.decode(self._encoding, errors=... | 288,676 |
Returns a reader that processes each row and yields dictionaries.
csv.DictReader does this job well for single-character delimiters; parsers
that need multi-character delimiters need to override this method.
Args:
line_reader (iter): yields lines from a file-like object.
Returns:
iter: a ... | def _CreateDictReader(self, line_reader):
delimiter = self.DELIMITER
quotechar = self.QUOTE_CHAR
magic_test_string = self._MAGIC_TEST_STRING
# Python 3 csv module requires arguments to constructor to be of type str.
if py2to3.PY_3:
delimiter = delimiter.decode(self._encoding)
quotec... | 288,677 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.