def get_model_data(model_name, store_type): if store_type == 'list': res = demisto.executeCommand("getList", {"listName": model_name}) res = res[0] if is_error(res): return_error("error reading list %s from Demisto" % model_name) return res["Contents"] elif store_type == 'mlModel': res = demisto.executeCommand("getMLModel", {"modelName": model_name}) res = res[0] if is_error(res): return_error("error reading model %s from Demisto" % model_name) return res['Contents']['modelData']
def predict_phishing_words(model_name, model_store_type, email_subject, email_body): model_data = get_model_data(model_name, model_store_type) model = demisto_ml.decode_model(model_data) text = "%s %s" % (email_subject, email_body) res = demisto.executeCommand('WordTokenizerNLP', {'value': text, 'hashWordWithSeed': demisto.args().get('hashSeed')}) if is_error(res[0]): return_error(res[0]['Contents']) tokenized_text_result = res[0]['Contents'] input_text = tokenized_text_result['hashedTokenizedText'] if tokenized_text_result.get('hashedTokenizedText') else \ tokenized_text_result['tokenizedText'] filtered_text, filtered_text_number_of_words = demisto_ml.filter_model_words(input_text, model) if filtered_text_number_of_words == 0: return_error("The model does not contains any of the input text words") explain_result = demisto_ml.explain_model_words(model, input_text, float(demisto.args().get('labelProbabilityThreshold', 0)), float(demisto.args().get('wordThreshold', 0)), int(demisto.args()['topWordsLimit'])) if tokenized_text_result.get('hashedTokenizedText'): hash_word_to_plain = dict( zip(tokenized_text_result['hashedTokenizedText'].split(" "), tokenized_text_result['tokenizedText'].split(" "))) explain_result['PositiveWords'] = map(lambda x: hash_word_to_plain[x], explain_result['PositiveWords']) explain_result['NegativeWords'] = map(lambda x: hash_word_to_plain[x], explain_result['NegativeWords']) explain_result['OriginalText'] = tokenized_text_result['originalText'] explain_result['TextTokensHighlighted'] = tokenized_text_result['tokenizedText'] res = demisto.executeCommand('HighlightWords', {'text': tokenized_text_result['tokenizedText'], 'terms': ",".join(explain_result['PositiveWords'])}) res = res[0] if not is_error(res): highlighted_text_markdown = res['Contents'] explain_result['TextTokensHighlighted'] = highlighted_text_markdown return { 'Type': entryTypes['note'], 'Contents': explain_result, 'ContentsFormat': formats['json'], 'HumanReadable': tableToMarkdown('DBot Predict Phihsing Words', explain_result, headers=['TextTokensHighlighted', 'Label', 'Probability', 'PositiveWords', 'NegativeWords'], removeNull=True), 'HumanReadableFormat': formats['markdown'], 'EntryContext': { 'DBotPredictPhishingWords': explain_result } }
def get_entry_from_args(): """ Handle finding the file entry using the user supplied arguments return the entry or quits script entirely. :rtype: object containing the entry of the found file and the entry_id or error & exit """ # Get the pcap file from arguments entry_id = None if 'pcapFileName' in demisto.args() \ and 'entryID' not in demisto.args(): PCAP_FILE = demisto.args()["pcapFileName"] entry_id = _find_entry_id_by_name(PCAP_FILE, [".pcap", ".cap", ".pcapng"]) elif 'entryID' in demisto.args(): entry_id = demisto.args()["entryID"] else: return_error('You must set pcapFileName or entryID when executing the PcapHTTPExtract script.') res = demisto.executeCommand('getFilePath', {'id': entry_id}) if len(res) > 0 and res[0]['Type'] == entryTypes['error']: return_error(f'Failed to get the file path for entry: {entry_id}') return res, entry_id
def process_field_id(command, command_args): """ Execute the command with given command args and process the results. :type command: ``str`` :param command: command name :type command_args: ``dict`` :param command_args: JSON of command arguments :return: field_id :rtype: ``str`` """ field_results = demisto.executeCommand(command, args=command_args) field_data = demisto.get(field_results[0], 'Contents') message_type = find_entry_type(demisto.get(field_results[0], 'Type')) if not field_data: human_readable_from_get_command = demisto.get(field_results[0], "HumanReadable") if human_readable_from_get_command: show_service_request_result(message_type, human_readable_from_get_command) show_service_request_result("error", ERROR_MESSAGES + json.dumps(field_results)) if isinstance(field_data, dict): all_fields = demisto.get(field_data, "records") if all_fields: return demisto.get(all_fields[0], "Id") elif isinstance(field_data, list): final_field = demisto.get(field_data[0], "Id") if final_field: return final_field else: show_service_request_result(message_type, field_data)
def main(): try: # To prevent the split from succeeding. indicators = argToList(demisto.args()['indicator'], separator='NoSeparatorWillBeFound') for indicator in indicators: resp = demisto.executeCommand("getIndicator", {'value': indicator}) if isError(resp) or not resp: demisto.results(resp) continue data = resp[0].get("Contents") if not data: demisto.results( "No results found for indicator {} .".format(indicator)) continue dbot_scores = [] for entry in data: for dbot_score, results in iterate_indicator_entry( indicator, entry): demisto.results(results) dbot_scores.append(dbot_score) dbot_scores = dbot_scores if len( dbot_scores) > 1 or not dbot_scores else dbot_scores[0] appendContext(CONTEXT_PATH, dbot_scores) except Exception as error: return_error(str(error), error)
def get_all_incidents_for_time_window_and_type(populate_fields: List[str], from_date: str, to_date: str, query_sup: str, limit: int, incident_type: str): # type: ignore """ Get incidents with given parameters and return list of incidents :param populate_fields: List of field to populate :param from_date: from_date :param to_date: to_date :param query_sup: additional criteria for the query :param limit: maximum number of incident to fetch :param incident_type: type of incident to fetch :return: list of incident """ msg = "" if query_sup: query = " %s" % query_sup else: query = "" res = demisto.executeCommand('GetIncidentsByQuery', { 'query': query, 'populateFields': ' , '.join(populate_fields), 'fromDate': from_date, 'toDate': to_date, 'limit': str(limit), 'incidentTypes': incident_type }) if is_error(res): return_error(res) incidents = json.loads(res[0]['Contents']) if len(incidents) == 0: msg += "%s \n" % MESSAGE_NO_INCIDENT_FETCHED return None, msg # type: ignore if len(incidents) == limit: msg += "%s \n" % MESSAGE_WARNING_TRUNCATED % (str(len(incidents)), str(limit)) return incidents, msg # type: ignore return incidents, msg # type: ignore
def main(): input_args = demisto.args() set_incidents_fields_names(input_args) default_args = get_args_based_on_last_execution() get_incidents_by_query_args = determine_incidents_args( input_args, default_args) incidents_query_res = demisto.executeCommand('GetIncidentsByQuery', get_incidents_by_query_args) if is_error(incidents_query_res): return_error(get_error(incidents_query_res)) incidents = json.loads(incidents_query_res[-1]['Contents']) if len(incidents) == 0: demisto.results('No results were found') else: tag_field = demisto.args().get('tagField', None) data = extract_data_from_incidents(incidents, tag_field) data_str = json.dumps(data) compress = demisto.args().get('compress', 'True') == 'True' if compress: encoded_data = data_str.encode('utf-8', errors='ignore') compressed_data = zlib.compress(encoded_data, 4) compressed_hr_data = b64encode(compressed_data).decode('utf-8') else: compressed_hr_data = data_str res = { 'PayloadVersion': FETCH_DATA_VERSION, 'PayloadData': compressed_hr_data, 'ExecutionTime': datetime.now().strftime("%Y-%m-%dT%H:%M:%S"), 'IsCompressed': compress } return_file = input_args.get('toFile', 'False').strip() == 'True' if return_file: return_file_entry(res, len(data['X'])) else: return_json_entry(res)
def install_packs(self, packs_to_install: List[Dict[str, str]]) -> None: """Sends the request to install the packs in the machine. Args: packs_to_install (List[Dict[str, str]]): The packs data to be used for the installation. """ if not packs_to_install: demisto.debug( f'{SCRIPT_NAME} - No packs were sent for installation.') return data = {'packs': packs_to_install, 'ignoreWarnings': True} # make the pack installation request packs_names_versions = { pack['id']: parse(pack['version']) for pack in packs_to_install } demisto.debug( f'{SCRIPT_NAME} - Sending installation request for: {packs_names_versions}' ) res = demisto.executeCommand('demisto-api-post', { 'uri': '/contentpacks/marketplace/install', 'body': data }) if is_error(res): error_message = f'{SCRIPT_NAME} - {get_error(res)}' demisto.debug(error_message) raise DemistoException(error_message) self.installed_packs.update(packs_names_versions) self.newly_installed_packs.update( packs_names_versions) # type: ignore[arg-type]
def search_indicators(args): keys = [ 'id', 'value', 'CustomFields', 'type', 'score', 'firstSeen', 'lastSeen', 'expiration', 'expirationStatus', 'sourceBrands', 'sourceInstances' ] query = args.get('query', None) if not query: raise ValueError('Query not set!') size = int(args.get('size', DEFAULT_SIZE)) indicators = demisto.executeCommand("findIndicators", { "query": query, 'size': size }) outputs = list() if not isinstance( indicators, list) or len(indicators) < 1 or 'Contents' not in indicators[0]: raise ValueError('No content') for i in indicators[0]['Contents']: oi = dict() for k in i.keys(): if k in keys: oi[k] = i[k] outputs.append(oi) return CommandResults(outputs_prefix='FoundIndicators', outputs_key_field='value', outputs=outputs)
def _add_campaign_to_incident(incident_id, campaign_id): res = demisto.executeCommand('setIncident', {'id': incident_id, 'customFields': {'partofcampaign': campaign_id}}) if is_error(res): return_error('Failed to add campaign data to incident {}. Error details:\n{}'.format(incident_id, get_error(res))) demisto.debug(f"Added campaign {campaign_id} to incident {incident_id}")
def perform_reopen(ids, action): for incident_id in ids: res = demisto.executeCommand("reopenInvestigation", {'id': incident_id}) if isError(res): return_error(COMMAND_ERROR_MSG.format(action=action, ids=','.join(ids), error=get_error(res))) return COMMAND_SUCCESS.format(action='reopened', ids=','.join(ids))
def main(): args = demisto.args() try: # Normalize grid id from any form to connected lower words, e.g. my_word/myWord -> myword grid_id = normalized_string(args.get('grid_id')) context_path = args.get('context_path') # Build updated table table = build_grid_command( grid_id=grid_id, context_path=context_path, keys=argToList(args.get('keys')), overwrite=argToBoolean(args.get('overwrite')), columns=argToList(args.get('columns')), sort_by=args.get('sort_by'), unpack_nested_elements=argToBoolean( args.get('unpack_nested_elements')), ) # Execute automation 'setIncident` which change the Context data in the incident res = demisto.executeCommand("setIncident", { 'customFields': { grid_id: table, }, }) if is_error(res): demisto.error( f'failed to execute "setIncident" with table: {table}') return_results(res) else: return_results( f'Set grid {grid_id} using {context_path} successfully.') except Exception as exc: return_error(f'Failed to execute setGridField. Error: {str(exc)}', error=traceback.format_exc())
def create_indicators(args: dict): """ When the create_indicator argument is set to True, create the new indicator first. :type args: ``dict`` :param args: dict of arguments of the command. :return: return a list of errors, empty if no errors. :rtype: ``None`` """ entity_b_to_create = remove_existing_entity_b_indicators(argToList(args.get('entity_b')), args.get('entity_b_query', '')) indicators = [] for entity_b in entity_b_to_create: indicator = { 'value': entity_b, 'type': args.get('entity_b_type'), } indicators.append(indicator) errors = list() for indicator in indicators: res = demisto.executeCommand("createNewIndicator", indicator) if is_error(res[0]): errors.append("Error creating indicator - {}".format(res[0]["Contents"])) demisto.debug( f"Create Indicators From CreateIndicatorRelationship automation: {len(indicators) - len(errors)}" f" indicators were created with values {str(indicators)}" ) if errors: demisto.debug(f'Errors were found while creating indicators from CreateIndicatorRelationships automation:' f' {json.dumps(errors, indent=4)}')
def get_existing_incidents(input_args, current_incident_type): global DEFAULT_ARGS get_incidents_args = {} get_incidents_args['limit'] = input_args.get('limit', DEFAULT_ARGS['limit']) if 'exsitingIncidentsLookback' in input_args: get_incidents_args['fromDate'] = input_args['exsitingIncidentsLookback'] elif 'exsitingIncidentsLookback' in DEFAULT_ARGS: get_incidents_args['fromDate'] = DEFAULT_ARGS['exsitingIncidentsLookback'] status_scope = input_args.get('statusScope', 'All') query_components = [] if 'query' in input_args: query_components.append(input_args['query']) if status_scope == 'ClosedOnly': query_components.append('status:closed') elif status_scope == 'NonClosedOnly': query_components.append('-status:closed') elif status_scope == 'All': pass else: return_error('Unsupported statusScope: {}'.format(status_scope)) type_values = input_args.get('incidentTypes', current_incident_type) if type_values != IGNORE_INCIDENT_TYPE_VALUE: type_field = input_args.get('incidentTypeFieldName', 'type') type_query = generate_incident_type_query_component(type_field, type_values) query_components.append(type_query) if len(query_components) > 0: get_incidents_args['query'] = ' and '.join('({})'.format(c) for c in query_components) incidents_query_res = demisto.executeCommand('GetIncidentsByQuery', get_incidents_args) if is_error(incidents_query_res): return_error(get_error(incidents_query_res)) incidents = json.loads(incidents_query_res[-1]['Contents']) return incidents
def jq_wrap(json_str, query): j = json.loads(json_str) res = pyjq.all(query, j) cmd_res = demisto.executeCommand('Set', {'key': 'jq.result', 'value': res}) if not is_error(cmd_res): return_results(res)
def update_incident_with_required_keys(incidents, required_keys): """ Update the given incident dict (from context) with values retrieved by GetIncidentsByQuery command :type incidents: ``list`` :param incidents: campaign incidents from the context :type required_keys: ``list`` :param required_keys: keys need to be updated """ ids = [str(incident['id']) for incident in incidents] res = demisto.executeCommand('GetIncidentsByQuery', {'query': "id:({})".format(' '.join(ids))}) if isError(res): return_error( f'Error occurred while trying to get incidents by query: {get_error(res)}' ) incidents_from_query = json.loads(res[0]['Contents']) id_to_updated_incident_map = { incident['id']: incident for incident in incidents_from_query } for incident in incidents: updated_incident = id_to_updated_incident_map[incident['id']] for key in required_keys: incident[key] = updated_incident.get(key)
def main(): try: args = demisto.args() entities = args.get('entities', '') entities_types = args.get('entities_types', '') relationships = args.get('relationships', '') limit = int(args.get('limit')) verbose = argToBoolean(args.get('verbose', 'false')) revoked = argToBoolean(args.get('revoked', 'false')) query = 'revoked:T' if revoked else 'revoked:F' res = demisto.executeCommand("searchRelationships", {'entities': entities, 'entityTypes': entities_types, 'relationshipNames': relationships, 'size': limit, 'query': query}) if is_error(res[0]): raise Exception("Error in searchRelationships command - {}".format(res[0]["Contents"])) relationships = res[0].get('Contents', {}).get('data', []) if relationships: context = to_context(relationships, verbose) else: context = [] hr = tableToMarkdown('Relationships', context, headers=['EntityA', 'EntityAType', 'EntityB', 'EntityBType', 'Relationship'], headerTransform=lambda header: re.sub(r"\B([A-Z])", r" \1", header)) return_results( CommandResults(readable_output=hr, outputs_prefix='Relationships', outputs=context, outputs_key_field='ID')) except Exception as e: demisto.error(traceback.format_exc()) return_error(f'Failed to execute SearchIndicatorRelationships automation. Error: {str(e)}')
def main(): get_users_response: List = demisto.executeCommand('getUsers', {'onCall': True}) if is_error(get_users_response): demisto.error(f'Failed to get users on call: {str(get_error(get_users_response))}') else: number_of_users_on_call = len(get_users_response[0]['Contents']) demisto.results(number_of_users_on_call)
def main(): list_data = demisto.executeCommand("getList", {"listName": "XSOAR Health - Failed Integrations Table"}) list_content = list_data[0].get('Contents', '') list_table = [] if list_content: list_json = json.loads(list_content) else: list_json = None if isinstance(list_json, list): for instance in list_json: list_table.append({"Brand": instance.get('brand'), "Instance": instance.get('instance'), "Category": instance.get('category'), "Information": instance.get('information')}) demisto.results({'total': len(list_table), 'data': list_table}) elif isinstance(list_json, dict): list_table.append({"Brand": list_json.get('brand'), "Instance": list_json.get('instance'), "Category": list_json.get('category'), "Information": list_json.get('information')}) demisto.results({'total': len(list_table), 'data': list_table}) else: data = {"total": 1, "data": [{"Brand": "N\\A", "Instance": "N\\A", "Category": "N\\A", "Information": "N\\A"}]} demisto.results(data)
def get_pack_data_from_marketplace(self, pack_id) -> Dict[str, str]: """Returns the marketplace's data for a specific pack. Args: pack_id (str): The pack ID for which to get the data. Returns: Dict[str, str]. The pack's data from marketplace. """ if pack_id in self.packs_data: demisto.debug( f'{SCRIPT_NAME} - Using cached data of {pack_id} that already been fetched.' ) return self.packs_data[pack_id] demisto.debug( f'{SCRIPT_NAME} - Fetching {pack_id} data from marketplace.') res = demisto.executeCommand( 'demisto-api-get', {'uri': f'/contentpacks/marketplace/{pack_id}'}) if is_error(res): error_message = f'{SCRIPT_NAME} - {get_error(res)}' demisto.debug(error_message) self.packs_data[pack_id] = res return res[0]
def main(): try: indicator = demisto.args()['indicator'] resp = demisto.executeCommand("getIndicator", {'value': indicator}) if isError(resp) or not resp: demisto.results(resp) return data = resp[0].get("Contents") if not data: demisto.results("No results.") return dbot_scores = [] for entry in data: for dbot_score, results in iterate_indicator_entry( indicator, entry): demisto.results(results) dbot_scores.append(dbot_score) dbot_scores = dbot_scores if len( dbot_scores) > 1 or not dbot_scores else dbot_scores[0] appendContext(CONTEXT_PATH, dbot_scores) except Exception as error: return_error(str(error), error)
def get_latest_incident_from_xdr(incident_id): # get the latest incident from xdr latest_incident_in_xdr_result = demisto.executeCommand( "xdr-get-incident-extra-data", {"incident_id": incident_id}) if is_error(latest_incident_in_xdr_result): raise ValueError( "Failed to execute xdr-get-incident-extra-data command. Error: {}". format(get_error(latest_incident_in_xdr_result))) latest_incident_in_xdr = latest_incident_in_xdr_result[0]["Contents"].get( "incident") # no need to pass the whole incident with extra data - it will be too big json to pass # just the basic incident details if 'alerts' in latest_incident_in_xdr: del latest_incident_in_xdr['alerts'] if 'file_artifacts' in latest_incident_in_xdr: del latest_incident_in_xdr['file_artifacts'] if 'network_artifacts' in latest_incident_in_xdr: del latest_incident_in_xdr['network_artifacts'] latest_incident_in_xdr_markdown = latest_incident_in_xdr_result[0][ "HumanReadable"] if not latest_incident_in_xdr: raise ValueError( "Error - for some reason xdr-get-incident-extra-data didn't return any incident from xdr " "with id={}".format(incident_id)) return latest_incident_in_xdr_result, latest_incident_in_xdr, latest_incident_in_xdr_markdown
def search_existing_job(job_name: str) -> Dict[str, Any]: """Searches the machine for previously configured jobs with the given name. Args: job_name (str): The name of the job to update it's past configurations. Returns: Dict[str, Any]. The job data as configured on the machine. """ body = { 'page': 0, 'size': 1, 'query': f'name:"{job_name}"', } res = demisto.executeCommand('demisto-api-post', { 'uri': '/jobs/search', 'body': body }) if is_error(res): error_message = f'{SCRIPT_NAME} - {get_error(res)}' demisto.debug(error_message) return {} search_results = res[0].get('Contents', {}).get('response', {}).get('data') if search_results: return search_results[0] return {}
def main(): global EMAIL_BODY_FIELD, EMAIL_SUBJECT_FIELD, EMAIL_HTML_FIELD, FROM_FIELD, SELF_IN_CONTEXT input_args = demisto.args() EMAIL_BODY_FIELD = input_args.get('emailBody', EMAIL_BODY_FIELD) EMAIL_SUBJECT_FIELD = input_args.get('emailSubject', EMAIL_SUBJECT_FIELD) EMAIL_HTML_FIELD = input_args.get('emailBodyHTML', EMAIL_HTML_FIELD) FROM_FIELD = input_args.get('emailFrom', FROM_FIELD) fields_to_display = input_args.get('fieldsToDisplay') SELF_IN_CONTEXT = argToBoolean(input_args.get('includeSelf', 'false')) if fields_to_display is not None: input_args['populateFields'] = fields_to_display fields_to_display = get_comma_sep_list(fields_to_display) else: fields_to_display = [] res = demisto.executeCommand('FindDuplicateEmailIncidents', input_args) if is_error(res): return_error(get_error(res)) res = res[-1] incidents = json.loads(res['Contents']) if is_number_of_incidents_too_low(res, incidents): return if is_number_of_unique_recipients_is_too_low(incidents): return analyze_incidents_campaign(incidents, fields_to_display)
def configure_job(job_name: str, existing_job: Optional[Dict[str, Any]] = None) -> bool: """Configures the job in the XSOAR instance. """ instance_context = demisto.context() job_params = existing_job or {} for job in instance_context.get('ConfigurationSetup', {}).get('Jobs', []): if job.get('name') == job_name: job_params.update(job) break if not job_params: return False res = demisto.executeCommand('demisto-api-post', { 'uri': '/jobs', 'body': job_params }) if is_error(res): error_message = f'{SCRIPT_NAME} - {get_error(res)}' demisto.debug(error_message) return_error(error_message) return False return True
def get_firewall_serials(pan_os_integration_instance_name: str) -> list: """ :param pan_os_integration_instance_name: Name of the instance of the PAN-OS integration. :return: List of the FWs serials associated with this instance. """ fw_monitor_list: list = [] fw_query = { 'type': 'op', 'cmd': '<show><devices><all></all></devices></show>', 'raw-response': 'true', 'using': pan_os_integration_instance_name } fw_query_result = demisto.executeCommand("pan-os", fw_query) if is_error(fw_query_result): raise Exception( f'Querying the instance: {pan_os_integration_instance_name} in Cortex Data Lake failed.' f' {fw_query_result[0]["Contents"]}') if fw_query_result and isinstance(fw_query_result, list): for fw in fw_query_result[0]['Contents']['response']['result'][ 'devices']['entry']: fw_monitor_list.append(fw['serial']) else: raise Exception( "Failed to retrieve Firewalls list from PAn-OS, try to specify manually a list of serials." ) return fw_monitor_list
def get_cisco_ise_active_instance_or_err_msg(): """ Get ise node details for all configured instances and determine which on is active/primary. All gather error messages if possible for nodes that are not in active state or have connnectivity issues. """ err_msg = [] active_instance = None # run common on all configured Cisco ISE nodes response = demisto.executeCommand("cisco-ise-get-nodes", {}) for resp in response: local_instance = resp['ModuleName'] if isError(resp): err = resp['Contents'] err_msg.append( f'{err.split("-")[0]} , instance name = {local_instance}') else: # Check if the output has any node that matches the local instance # and is also a primary or is in standalone mode for node_data in resp['Contents']['CiscoISE.NodesData']: if node_data['isLocalIstance']: if node_data['inDeployment'] is False or ( node_data['inDeployment'] is True and node_data['primaryPapNode'] is True): active_instance = local_instance return active_instance, err_msg
def _find_entry_id_by_name(file_name, extensions=None): """ Scan all entries and find corresponding entry id by file name extensions, an array used to furthur filter the entries. :param file_name: find by file name. :param extensions: filter more by the file extension. :return: the found entryID """ entries = demisto.executeCommand('getEntries', {}) found_entry_id = None for entry in entries: entry_file_name = demisto.get(entry, 'File') is_correct_file = file_name.lower() == entry_file_name.lower() has_correct_extension = _file_has_extension(file_name, extensions) if extensions else True if is_correct_file and has_correct_extension: found_entry_id = entry['ID'] break if not found_entry_id: demisto.results({"Type": entryTypes["note"], "ContentsFormat": formats["markdown"], "Contents": "### No file found", "EntryContext": {"PcapHTTPExtractor.Flows": []} }) sys.exit(0) return found_entry_id
def main(): try: if is_demisto_version_ge("6.2.0"): raise DemistoException( "This script has been deprecated. Please checkout the System Diagnostic page for an " "alternative.") args = demisto.args() is_table_result = argToBoolean(args.get('table_result', False)) raw_output = demisto.executeCommand('GetLargestInvestigations', args={ 'from': args.get('from'), 'to': args.get('to'), 'table_result': 'true', }) if is_error(raw_output): raise DemistoException( f'Failed to run GetLargestInvestigations:\n{get_error(raw_output)}' ) investigations = raw_output[0].get('Contents', {}).get('data') data = get_extra_data_from_investigations(investigations) if not is_table_result: return_results( tableToMarkdown('Largest Inputs And Outputs In Incidents', data)) else: return_results(data) except Exception as exc: return_error( f'Failed to execute GetLargestInputsAndOuputsInIncidents.\nError: {exc}', error=exc)
def health_check_command(args: Dict[str, Any]) -> CommandResults: integration_name = args.get('integration_name', '') raw_result = demisto.executeCommand( "demisto-api-post", { "uri": "/settings/integration/search", "body": { "size": 10, "query": "name:" + integration_name }, }) if is_error(raw_result): return_error(get_error(raw_result)) health_dict = raw_result[0]["Contents"]["response"]["health"] is_healthy, fetch_done = health_check(health_dict, integration_name) return CommandResults( outputs_prefix='IntegrationHealth', outputs_key_field='integrationName', outputs={ 'isHealthy': is_healthy, 'fetchDone': fetch_done, 'integrationName': integration_name }, )
def get_incident_by_query(query): """ Get a query and return all incidents details matching the given query. Args: query: Query for the incidents that should be returned. Returns: dict. The details of all incidents matching the query. """ # In order to avoid performance issues, limit the number of days to query back for modified incidents. By default # the limit is 60 days and can be modified by the user by adding a list called # `XSOAR - Email Communication Days To Query` (see README for more information). query_time = get_query_window() query_from_date = str(parse_date_range(query_time)[0]) res = demisto.executeCommand( "GetIncidentsByQuery", { "query": query, "fromDate": query_from_date, "timeField": "modified", "Contents": "id,status" })[0] if is_error(res): demisto.results( ERROR_TEMPLATE.format('GetIncidentsByQuery', res['Contents'])) raise DemistoException( ERROR_TEMPLATE.format('GetIncidentsByQuery', res['Contents'])) incidents_details = json.loads(res['Contents']) return incidents_details
def main(): incident_id = demisto.args()['id'] if 'id' in demisto.args( ) else demisto.incidents()[0]['id'] key = demisto.args()['key'] value = demisto.args()['value'] append = demisto.args()['append'] error_unfinished = argToBoolean(demisto.args().get('errorUnfinished', "false")) args = {'key': key, 'value': value, 'append': append} res = demisto.executeCommand('executeCommandAt', { 'incidents': incident_id, 'command': 'Set', 'arguments': args, }) if error_unfinished: result_string = res[-1].get('Contents', "") result_string = result_string.strip('.') numbers = [int(s) for s in result_string.split() if s.isdigit()] if len( set(numbers) ) > 1: # check if all the numbers are the same. Supposed to be 2 numbers. # if the numbers are the same, Set succeed on all of the incidents. return_error("Not all incidents were set.\n" + result_string) demisto.results(res)
def main(): LIST_NAME = demisto.args()['listName'] TO_ZIP = (demisto.args()['zipFile'] == 'true') entry_id = demisto.args()['entryId'] res = demisto.getFilePath(entry_id) if not res: return_error("Entry {} not found".format(entry_id)) file_path = res['path'] file_base64 = get_file_data(file_path, TO_ZIP) res = demisto.executeCommand("createList", {"listName": LIST_NAME, "listData": file_base64}) if isError(res): return res return { 'Contents': file_base64, 'ContentsFormat': formats['text'], 'HumanReadable': tableToMarkdown('Success store file in list', { 'File Entry ID': entry_id, 'List Name': LIST_NAME, 'Size': len(file_base64) }), 'HumanReadableFormat': formats['markdown'], }
def generate_command_example(cmd, cmd_example): errors = [] context_example = '' md_example = '' if cmd_example != '': try: example_cmd, kwargs = extract_command(cmd_example) res = demisto.executeCommand(example_cmd, kwargs) for entry in res: if is_error(entry): demisto.results(res) raise RuntimeError('something went wrong with your command: {}'.format(cmd_example)) raw_context = entry.get('EntryContext', {}) if raw_context is not None: context = {k.split('(')[0]: v for k, v in raw_context.items()} context_example += json.dumps(context, indent=4) if entry.get('HumanReadable') is None: if entry.get('Contents') is not None: content = entry.get('Contents') if isinstance(content, STRING_TYPES): md_example += content else: md_example += json.dumps(content) else: md_example += entry.get('HumanReadable') except RuntimeError: errors.append('The provided example for cmd {} has failed...'.format(cmd['name'])) except Exception as e: errors.append( 'Error encountered in the processing of command {}, error was: {}. '.format(cmd['name'], str(e)) + 'Please check your command inputs and outputs') else: errors.append('did not get any example for {}. please add it manually.'.format(cmd['name'])) example = [ '', '##### Command Example', '`{}`'.format(cmd_example), '', '##### Context Example', '```', '{}'.format(context_example), '```', '', '##### Human Readable Output', '{}'.format(md_example), '', ] return example, errors
FIELDS = { 'Description': args.get('description'), 'Priority': args.get('priority'), 'CustomerDisplayName': args.get('customer_display_name'), 'OwnedBy': args.get('owned_by'), 'Service': args.get('service') } # #################################################################################### # ############################## EXECUTION PART ###################################### # #################################################################################### def build_arguments(): arguments = { 'type': BUSINESS_OBJECT_TYPE, 'id_type': args.get('id_type'), 'id_value': args.get('id_value'), # As `owned_by` and `service` arguments are not mandatory we make sure to remove them by using the createContext # function with removeNull flag set to true. # If all script arguments are mandatory, it would be sufficient to use `json: FIELDS` instead of # `createContext(FIELDS, removeNull=True)` 'json': createContext(FIELDS, removeNull=True) } return arguments result = demisto.executeCommand('cherwell-update-business-object', build_arguments()) demisto.results(result)