Script Code Snippets - Python Development Quick Start Guide - 6.x - Cortex XSOAR - Cortex - Security Operations

Cortex XSOAR Python Development Quick Start Guide

Product
Cortex XSOAR
Version
6.x
Creation date
2023-03-22
Last date published
2023-08-31
Category
Python Development Quick Start Guide

The following code snippets perform common actions that you can modify as needed.

Basic Automation Template

This template can be used to create a new automation, replacing the standard boilerplate provided.

def main():
    try:
    except Exception as ex:
        demisto.error(traceback.format_exc())
        return_error("Failed to execute command: " + str(ex))
if __name__ in ("__main__", "__builtin__", "builtins"):    
    main()

Return Results to War Room and Incident Context

The Common Server Python return_results() function outputs data to both the War Room and incident context. A simple example is to display context data as Markdown in the War Room and update context. The Common Server Python functions tableToMarkdown() and CommandResults() are used to prepare the results and then pass them to return_results().

markDown   = tableToMarkdown("Table Name", outputContext)
resultsOut = CommandResults(
	readable_output	     = markDown,
        outputs_prefix 	     = "context.path",
        outputs_key_field    = "contextFieldName",
        outputs 	     = outputContext
)
return_results(resultsOut)

Log Errors to Cortex XSOAR Server Log

The Demisto class provides the demisto.error() function that logs errors to the Cortex XSOAR server log.

message = "An error message to log"
argDict	= {'name': "MyAutomationName", 'value': 0}
demisto.error(message, argDict)

Log Errors to the War Room

The Common Server Python return_error() function creates error entries in the War Room.

message     = "An error message to display"	
return_error(message)

An exception string can be included in the message if using try/catch to handle exceptions.

try:
	## code  ##
except Exception as ex:
	message    = "An error message to display: "
        return_error(message + str(ex))

Access Arguments

The Demisto class provides the demisto.args() function to retrieve arguments passed to an automation script, for example if a Cortex XSOAR playbook task calls the automation script.

To retrieve multiple arguments in a Python dictionary:

argDict    = demisto.args()
argValue1  = argDict['argumentName1']
argValue2  = argDict['argumentName2']

If only a single argument is required, access the argument directly with a key name:

argValue 	= demisto.args()['argumentName']

Access Incident Objects

The demisto.incident() function returns a Python dictionary of the incident field values.

incidentDict = demisto.incident()

If only a single field is required, access the field directly with a key name.

fieldValue   = demisto.incident()['fieldName']

Find, Set, and Create Indicators

The findIndicators command queries for indicators.

findParam = {
    'fromdate':"2021-10-27T15:00:00+07:00",
    'todate': 	"2021-10-28T15:00:00+07:00",
    'query': 	"type:file"
}
results = demisto.executeCommand("findIndicators", 
    findParam)[0]['Contents']

A request to the Cortex XSOAR API (required if applying tags) updates the indicator.

body = {
    'CustomFields':	{'tags': ["newtag"]},
    'id':		str(indId),
    'indicator_type':   indicator['indicator_type'],
    'value':		indicator['value']      
}
demisto.executeCommand("demisto-api-post",
    {'uri':"/indicator/edit", 'body':body})

Get and Set Incident Fields

To get incident field values, the demisto.incident() function returns a dictionary of all fields or a single field.

fieldDict    = demisto.incident()
fieldValue   = demisto.incident()['details']

To set the field value, the demisto.executeCommand() function passes a dictionary of field names and field values.

fieldValue = "new field value"
demisto.executeCommand("setIncident", {'details': fieldValue})

Get and Set Incident Custom Fields

Incidents may include custom fields created by the Cortex XSOAR user.  These are contained within the incident object as a sub-dictionary.  If there are multiple fields, use the demisto.incident() function with CustomFields as the key name.  Individual custom field values can then be retrieved from the dictionary.

customDict    = demisto.incident()['CustomFields']
fieldValue    = customDict['fieldName']

If only a single custom field is required:

fieldValue    = demisto.incident()['CustomFields']['fieldName']

To set a custom field, a Python dictionary object with a key name that matches the field name of the value is converted to a JSON string and the demisto.executeCommand() function is called.

value = json.dumps({'fieldname': fieldValue})
demisto.executeCommand("setIncident", {'customFields': value})

Note

When setting custom fields use customFields , and when retrieving custom fields use CustomFields.

Get and Set Grid Fields

Abstract

Get and set grid fields to display data in tables.

Grid fields display data tables. 

Note

Column names must be the machine name (lowercase version of the display name) for the column or the data is ignored.

gridDict = {
    "column1": "This is column 1",
    "column2": "This is column 2"
}
gridRows = json.dumps({ "gridfield": gridDict })
results  = demisto.executeCommand("setIncident", {
    'customFields': gridRows
})

Get and Set Incident Context

Abstract

Get incident context using demisto.context() and set incident context using demisto.setContext().

To get a context value:

contextDict   = demisto.context()
contextValue  = contextDict['context.path']

To set a context value, use the demisto.setContext() function:

contextPath   = 'context.path'
contextValue  = "context value"
demisto.setContext(contextPath, contextValue)

Get and Set Lists

Abstract

Get and set lists in Cortex XSOAR.

Lists are separate from incident fields and context, and store data for use by automations.  Two common list actions are getting and setting values in the list.

listDict = [
    { 'Name1': "val11", 'Name2': "val12",'Name3': "val13"},
    { 'Name1': "val21", 'Name2': "val22",'Name3': "val23"},
    { 'Name1': "val31", 'Name2': "val32",'Name3': "val33"},
    { 'Name1': "val41", 'Name2': "val42",'Name3': "val43"}
]
demisto.executeCommand("setList", {
    'listName': "Name of List",
    'listData': listDict})
listDict = demisto.executeCommand("getList", {
    'listName':"Name of List"
})[0]['Contents']

Invoke the Cortex XSOAR REST API

Abstract

Use the Cortex XSOAR REST API for automation tasks.

The Cortex XSOAR REST API is available for automation tasks that require different access than what is provided through automation scripts and commands.  See the API documentation for each endpoint to determine the parameters to include in the body of a request.

To invoke an API, specify the endpoint uri, in this case /incident, and provide the body of the request in a dictionary.  The following sample creates an incident with the name "Incident Name”.

requestDict = {'name': "Incident Name"}
response    = demisto.executeCommand(
    "demisto-api-post", 
    {'uri': "/incident", 'body': requestDict}
)[0]['Contents']['response']