Skip to main content

Demisto Class

All Python integrations and scripts have available as part of the runtime the demisto class object. The object exposes a series of API methods which are used to retrieve and send data to the Cortex XSOAR Server.

note

The demisto class is a low level API. For many operations we provide a simpler and more robust API as part of the Common Server Functions.

_apiCall#

demisto._apiCall(name, params=None, data=None)

Special apiCall to internal xdr api. Only available to OOB content.

Arguments:

  • name - name of the api (currently only wfReportIncorrectVerdict is supported)
  • params - url query args to pass. Use a dictionary such as: `{"key":"value"}
  • data - POST data as a string. Make sure to json.dumps.
  • Note - if data is empty then a GET request is performed instead of a POST.

Returns:

  • dict - The response of the api call

addEntry#

demisto.addEntry(id, entry, username=None, email=None, footer=None)

(Integration only) Adds an entry to a mirrored investigation war room

Arguments:

  • id str - Incident ID to add the entry in
  • entry str - The text to add in the entry
  • username str - The username of the user to be the entry creator (Default value = None)
  • email str - The email address of the user to be the entry creator (Default value = None)
  • footer str - The email address of the user to be the entry creator (Default value = None)

Returns:

  • None - No data returned

args#

demisto.args()

Retrieves a command / script arguments object

Returns:

  • dict - Arguments object

command#

demisto.command()

(Integration only) Retrieves the integration command that is being run

Returns:

  • str - Integrations command name

context#

demisto.context()

Retrieves the context data object of the current incident

Returns:

  • dict - Context data object

createIncidents#

demisto.createIncidents(incidents, lastRun=None, userID=None)

(Integration only) Creates incident in long running execution

Arguments:

  • incidents list - List of incident objects to create, with the following optional keys:
    • name (str)
    • type (str) - If not provided, an Unclassified incident will be created
    • labels (list) - List of {"type": , "value": } objects
    • rawJSON (str) - Will be omitted after the classification & mapping step
    • occurred (str)
    • details (str)
    • severity (int)
  • lastRun dict - the LastRun object to set (Default value = None)
  • userID str - The user associated with the request (Default value = None)

Returns:

Union[list, dict]: Created incident object

createIndicators#

demisto.createIndicators(indicators_batch, noUpdate=False)

(Integration only) Creates indicators from given indicator objects batch

Arguments:

  • indicators_batch list - List of indicators objects to create
  • noUpdate bool - No update on fetched feed (no new indicators to fetch), Available from Server version 6.5.0.

Returns:

  • None - No data returned

credentials#

demisto.credentials(credentials)

(Integration only) For integrations that support fetching credentials. Send the fetched credentials to the server.

Arguments:

  • credentials list - List of credential objects

Returns:

  • None - No data returned

debug#

demisto.debug(msg, *args)

Prints a message to the server logs in debug level

Arguments:

  • msg str - The message to be logged
  • args dict - Additional arguments to log

Returns:

  • None - No data returned

demistoUrls#

demisto.demistoUrls()

Retrieves the following URLs related to the incident.

  • evidenceBoard
  • investigation
  • relatedIncidents
  • server
  • warRoom
  • workPlan You can use these URLs when you send notifications outside the system over email or slack and would like to include a link to the incident.

Returns:

  • dict - Object contains server URLs with page as key and URL as value

demistoVersion#

demisto.demistoVersion()

Retrieves server version and build number

Returns:

  • dict - Objects contains server version and build number

directMessage#

demisto.directMessage(message, username=None, email=None, anyoneCanOpenIncidents=None)

(Integration only) Executes command provided in direct message to messaging bot

Arguments:

  • message str - The message sent in personal context
  • username str - The username of the user that sent the direct message (Default value = None)
  • email str - The email address of the user that sent the direct message (Default value = None)
  • anyoneCanOpenIncidents bool - Whether external users can create incidents or not (Default value = None)

Returns:

  • str - Server response to command executed in the direct message

dt#

demisto.dt(obj=None, trnsfrm=None)

Extracts field from object using DT language syntax

Arguments:

  • obj dict - The object to look in for the requested field (Default value = None)
  • trnsfrm str - The field to get value of (Default value = None)

Returns:

  • str - The field value in the object

error#

demisto.error(msg, *args)

Prints a message to the server logs in error level

Arguments:

  • msg str - The message to be logged
  • args dict - Additional arguments to log

Returns:

  • None - No data returned

executeCommand#

demisto.executeCommand(command, args)

(Script only) Executes given integration command / script and arguments

Arguments:

  • command str - Integration command name or script name to run
  • args dict - Integration command / script arguments

Returns:

Union[dict, list]: Command execution response wrapped in Demisto entry object

findUser#

demisto.findUser(username=None, email=None)

(Integration only) Looks up for a user in the system

Arguments:

  • username str - The username of the user to search for (Default value = None)
  • email str - The email address of the user to search for (Default value = None)

Returns:

  • dict - Object representing the user found

get#

demisto.get(obj, field, defaultParam=None)

Extracts field value from nested object

Arguments:

  • obj dict - The object to extract the field from
  • field str - The field to extract from the object, given in dot notation
  • defaultParam object - The default value to return in case the field doesn't exist in obj

Returns:

  • str - The value of the extracted field

getAllSupportedCommands#

demisto.getAllSupportedCommands()

(Script only) Retrieves all available integration commands and scripts

Returns:

  • dict - Object of all available integrations and scripts

getArg#

demisto.getArg(arg)

Extracts given argument from the arguments object

Arguments:

  • arg str - Argument to get value of

Returns:

  • str - Argument value

getAutoFocusApiKey#

demisto.getAutoFocusApiKey()

Retrieves the AutoFocus API Key related to this Cortex XSOAR License. You can use this API Key in all AutoFocus integrations and Feeds. This command is not available on tenants.

Returns:

  • str - String containing the API Key

getFilePath#

demisto.getFilePath(id)

Retrieves file path and name, given file entry ID

Arguments:

  • id str - File entry ID to get details of

Returns:

  • dict - Object contains file ID, path and name

getIndexHash#

demisto.getIndexHash()

(Integration only) Retrieves the hashed value of the tenant in which ran in

Returns:

  • str - Hashed value of tenant name

getIntegrationContext#

demisto.getIntegrationContext()

(Integration only) Retrieves the IntegrationContext object

Returns:

  • dict - IntegrationContext object

getIntegrationContextVersioned#

demisto.getIntegrationContextVersioned(refresh=False)

(Integration only) Retrieves the versioned IntegrationContext object

Arguments:

  • refresh bool - Whether to get the integration context straight from the DB and not from the instance memory. (Default value = False) # noqa

Returns:

  • dict - IntegrationContext versioned object

getLastMirrorRun#

demisto.getLastMirrorRun()

(Integration only) Retrieves the LastMirrorRun object

Returns:

  • dict - LastMirrorRun object

getLastRun#

demisto.getLastRun()

(Integration only) Retrieves the LastRun object

Returns:

  • dict - LastRun object

getLicenseCustomField#

demisto.getLicenseCustomField(key)

Get a custom field from content XSOAR configuration (can only be run in system integrations)

Arguments:

  • key str - The key name inside the content object to search for.

Returns:

  • str - the value stored in content object that matced the given key.

getLicenseID#

demisto.getLicenseID()

Retrieves the ID of the license used in the server

Returns:

  • str - The license ID

getParam#

demisto.getParam(param)

(Integration only) Extracts given parameter from the integration parameters object

Arguments:

  • param str - Integration parameter to get value of

Returns:

  • str - Integration parameter value

gets#

demisto.gets(obj, field)

Extracts field value from nested object

Arguments:

  • obj dict - The object to extract the field from
  • field str - The field to extract from the object, given in dot notation

Returns:

  • str - The value of the extracted field

handleEntitlementForUser#

demisto.handleEntitlementForUser(incidentID, guid, email, content, taskID="")

(Integration only) Sends request to server to process entitlement response given from messaging client

Arguments:

  • incidentID str - The incident ID in which the question was sent in
  • guid str - The entitlement UUID which identifies the question
  • email str - The email address of the user that responded
  • content str - The content of the response
  • taskID str - The playbook task ID to mark as complete (Default value = "")

Returns:

  • None - No data returned

incident#

demisto.incident()

Retrieves the current incident and all its fields (e.g. name, type). The incident custom fields will be populated as a dict under the CustomFields attribute (for example the filename custom field can be retrieved using demisto.incident()['CustomFields'].get('filename')).

demisto.incident gets the data from the script on the beginning of the execution, hence if updating the incident context during script execution, it won't be reflected when calling demisto.incident, which will return stale context data.

Returns:

  • dict - dict representing an incident object

incidents#

demisto.incidents(incidents=None)

In script, retrieves the Incidents list from the context In integration, used to return incidents to the server.

Arguments:

  • incidents list - In integration only, list of incident objects (Default value = None).

Returns:

  • list - List containing the current incident object.

info#

demisto.info(msg, *args)

Prints a message to the server logs in info level

Arguments:

  • msg str - The message to be logged
  • args dict - Additional arguments to log

Returns:

  • None - No data returned

integrationInstance#

demisto.integrationInstance()

(Integration only) Retrieves the integration instance name in which ran in

Returns:

  • str - The integration instance name

internalHttpRequest#

demisto.internalHttpRequest(method, uri, body=None)

Run an internal HTTP request to the XSOAR server. The request runs with the permissions of the executing user, when a command is being executed manually (such as via the War Room or when browsing a widget). When run via a playbook, will run with a readonly user with limited permissions isolated to the current incident only. Available for both Integrations and Scripts starting from Server version 6.1.

Arguments:

  • method str - HTTP method such as: GET or POST
  • uri str - Server uri to request. For example: "/contentpacks/marketplace/HelloWorld". body Optional[str]: Optional body for a POST request. Defaults to None.

Returns:

  • dict - dict cotainnig the following fields:
    • statusCode (int): HTTP status code such as 200
    • status (str): HTTP status line such as: "200 OK"
    • body (str): response body
    • headers (dict): dict of headers. Each key is a header name with an array of values. For example: "headers": {"Content-Type": ["text/plain; charset=utf-8"]}

investigation#

demisto.investigation()

Retrieves the ID of the investigation in which being run in

Returns:

  • dict - Object contains the investigation ID

log#

demisto.log(msg)

Prints a message to the current incidents war room log

Arguments:

  • msg str - The message to be logged

Returns:

  • None - No data returned

mapObject#

demisto.mapObject(obj, mapper, mapper_type)

Mapping an object using chosen mapper

Returns:

  • dict - the obj after mapping

mirrorInvestigation#

demisto.mirrorInvestigation(id, mirrorType, autoClose=False)

(Integration only) Marks an investigation as mirrored

Arguments:

  • id str - Incident ID to mirror
  • mirrorType str - Contains mirror type and mirror direction separated by colon, e.g. all:both
  • autoClose bool - Whether to close the investigation when the mirrored channel is closed/archived (Default value = False)

Returns:

  • None - No data returned

params#

demisto.params()

(Integration only) Retrieves the integration parameters object

Returns:

  • dict - Integrations parameters object

parentEntry#

demisto.parentEntry()

Retrieves information regarding the war room entry from which the method runs

Returns:

  • dict - information regarding the current war room entry

results#

demisto.results(results)

Outputs entries to the war-room

Arguments:

  • results Union[list, dict] - The entry object or array of entry objects to output

Returns:

  • None - No data returned

    An example of results argument:

{
Type: EntryType.NOTE,
Contents: data,
ContentsFormat: EntryFormat.JSON,
HumanReadable: md,
ReadableContentsFormat: EntryFormat.MARKDOWN,
EntryContext: context,
Tags: [tag1, tag2]
}

searchIndicators#

demisto.searchIndicators(fromDate='', query='', size=100, page=0, toDate='', value='', searchAfter=None, populateFields=None, **kwargs)

Searches for indicators according to given query. If using Elasticsearch with Cortex XSOAR 6.1 or later, the searchAfter argument must be used instead of the page argument.

Arguments:

  • fromdate str - The start date to search from (Default value = '')
  • query str - Indicator search query (Default value = '')
  • size int - Limit the number of returned results (Default value = 100)
  • page int - Response paging (Default value = 0)
  • todate str - The end date to search until to (Default value = '')
  • value str - The indicator value to search (Default value = '')
  • searchAfter str - Use the last searchIndicators() outputs for search batch (Default value = None)
  • populateFields str - Comma separated fields to filter (e.g. "value,type")

Returns:

  • dict - Object contains the search results

    You can searchIndicators one batch at a time, without needing to load all indicators at once, by adding the argument searchAfter after the demisto.executeCommand. When you run a search for the query type:IP, the return value includes searchAfter

>>> demisto.executeCommand(searchIndicators, "query": 'type:IP', "size" :1000})
{
"iocs": [],
"searchAfter": [1596106239679, dd7aa6abfcb3adf793922618005b2ad5],
"total": 7432
}

You can then use the returned value of searchAfter to iterate over all batches.

>>> res = demisto.executeCommand("searchIndicators", {"query" : 'type:IP', "size" : 1000})
>>> search_after_title = 'searchAfter'
>>> while search_after_title in res and res[search_after_title] is not None:
>>> demisto.results(res)
>>> res = demisto.executeCommand("searchIndicators",
>>> {"query" : 'type:IP', "size" : 1000, "searchAfter" : res[search_after_title]})

searchRelationships#

demisto.searchRelationships(args)

Retrieves Indicators Relationship data according to given filters.

Arguments:

  • args dict - The relationships filter object. A dictionary with the following keys:
    • size (int)
    • relationshipNames (List[str])
    • entities (List[str])
    • entityTypes (List[str])
    • excludedEntities (List[str])
    • query (str)
    • fromDate (str)
    • toDate (str)
    • searchAfter (List[str])
    • searchBefore (List[str])
    • sort (List[Dict[str, Any]])

Returns:

  • (dict) - The Relationship Search response.

    Example (partial results):

>>> demisto.searchRelationships({"entities": ["8.8.8.8", "google.com"], "size": 2})
{
"total": 2,
"data": [
{
"id": "27",
"entityA": "8.8.8.8",
"entityAFamily": "Indicator",
"entityAType": "IP",
"name": "contains",
"reverseName": "part-of",
"entityB": "1.1.1.1",
"entityBFamily": "Indicator",
"entityBType": "IP",
"type": "IndicatorToIndicator",
"createdInSystem": "2022-04-04T16:29:04.417942+03:00",
"sources": [
{
"reliability": "C - Fairly reliable",
}
]
},
{
"id": "26",
"entityA": "google.com",
"entityAFamily": "Indicator",
"entityAType": "Domain",
"name": "related-to",
"reverseName": "related-to",
"entityB": "bing.com",
"entityBFamily": "Indicator",
"entityBType": "Domain",
"type": "IndicatorToIndicator",
"createdInSystem": "2022-04-04T16:23:39.863033+03:00",
"updatedInSystemBySource": "2022-04-04T16:23:39.862853+03:00",
"sources": [
{
"reliability": "C - Fairly reliable",
}
]
}
],
"SearchAfter": [
" \u0001\u0016q-\u0006`Uy'p",
"26"
],
"SearchBefore": [
" \u0001\u0016q-\u0012\u0001\u0004n\u0013p",
"27"
]
}

setAssetsLastRun#

demisto.setAssetsLastRun(obj)

(Integration only) Stores given object in the AssetsLastRun object

Arguments:

  • obj dict - The object to store

Returns:

  • None - No data returned

setContext#

demisto.setContext(contextPath, value)

(Script only) Sets given value in path in the context data

Arguments:

  • contextPath str - The context data path to set the value in
  • value str - The value to set in the context data path

Returns:

  • dict - Object contains operation result status

setIntegrationContext#

demisto.setIntegrationContext(context)

(Integration only) Stores given object in the IntegrationContext object

Arguments:

  • context dict - The object to store

Returns:

  • None - No data returned

setIntegrationContextVersioned#

demisto.setIntegrationContextVersioned(context, version=-1, sync=False)

(Integration only) Stores given object in the IntegrationContext object in given version

Arguments:

  • context dict - The object to store
  • version int - The context version to set. If the version is older than the current, an error will be thrown. (Default value = -1) # noqa
  • sync bool - Whether to save the context to the DB right away. If false, the context will be saved at the end of the command. (Default value = False)

Returns:

  • None - No data returned

setLastMirrorRun#

demisto.setLastMirrorRun(obj)

(Integration only) Stores given object in the LastMirrorRun object

Arguments:

  • obj dict - The object to store

Returns:

  • None - No data returned

setLastRun#

demisto.setLastRun(obj)

(Integration only) Stores given object in the LastRun object

Arguments:

  • obj dict - The object to store

Returns:

  • None - No data returned

uniqueFile#

demisto.uniqueFile()

Generate a unique file name based upon a random UUID

Returns:

  • str - Random UUID

updateModuleHealth#

demisto.updateModuleHealth(data, is_error=False)

(Integration only) Updated integration module health with given message

Arguments:

  • data Union[str, dict] - Either the message to display in the integration module health, or a dictionary containing the "eventsPulled" field (number).
  • is_error bool - Whether or not to display it as an error message in the fetch history.

Returns:

  • None - No data returned