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#
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.headers- headers to pass. Use a dictionary such as:{"key":"value"}method- HTTP method to use.path- path to append to the base url.timeout- The amount of time (in seconds) that a request will wait for a client to send data before the request is aborted.response_data_type- The type of the response. should be None unless the response value is binary then it should be 'bin'.*Note if data is empty then a GET request is performed instead of a POST.
Returns:
dict- The response of the api call
_platformAPICall#
Special platform API call to interact with the platform's backend services. Only available to OOB content.
Arguments:
path- path to append to the base urlmethod- HTTP method to use (GET, POST, PUT, DELETE, etc.)params- url query args to pass. Use a dictionary such as:{"key":"value"}data- POST data as a dict.timeout- The amount of time (in seconds) that a request will wait for a client to send data before the request is aborted *Note if data is empty then a GET request is performed instead of a POST.
Returns:
dict- The response of the api call
addEntry#
(Integration only) Adds an entry to a mirrored investigation war room
Arguments:
idstr - Incident ID to add the entry inentrystr - The text to add in the entryusernamestr - The username of the user to be the entry creator (Default value = None)emailstr - The email address of the user to be the entry creator (Default value = None)footerstr - The email address of the user to be the entry creator (Default value = None)
Returns:
None- No data returned
args#
Retrieves a command / script arguments object
Returns:
dict- Arguments object
command#
(Integration only) Retrieves the integration command that is being run
Returns:
str- Integrations command name
context#
Retrieves the context data object of the current incident
Returns:
dict- Context data object
createIncidents#
(Integration only) Creates incident in long running execution
Arguments:
incidentslist - 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)
lastRundict - the LastRun object to set (Default value = None)userIDstr - The user associated with the request (Default value = None)
Returns:
Union[list, dict]: Created incident object
createIndicators#
(Integration only) Creates indicators from given indicator objects batch
Arguments:
indicators_batchlist - List of indicators objects to createnoUpdatebool - No update on fetched feed (no new indicators to fetch), Available from Server version 6.5.0.
Returns:
None- No data returned
credentials#
(Integration only) For integrations that support fetching credentials. Send the fetched credentials to the server.
Arguments:
credentialslist - List of credential objects
Returns:
None- No data returned
debug#
Prints a message to the server logs in debug level
Arguments:
msgstr - The message to be loggedargsdict - Additional arguments to log
Returns:
None- No data returned
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#
Retrieves server version and build number
Returns:
dict- Objects contains server version and build number
directMessage#
(Integration only) Executes command provided in direct message to messaging bot
Arguments:
messagestr - The message sent in personal contextusernamestr - The username of the user that sent the direct message (Default value = None)emailstr - The email address of the user that sent the direct message (Default value = None)anyoneCanOpenIncidentsbool - Whether external users can create incidents or not (Default value = None)
Returns:
str- Server response to command executed in the direct message
dt#
Extracts field from object using DT language syntax
Arguments:
objdict - The object to look in for the requested field (Default value = None)trnsfrmstr - The field to get value of (Default value = None)
Returns:
str- The field value in the object
error#
Prints a message to the server logs in error level
Arguments:
msgstr - The message to be loggedargsdict - Additional arguments to log
Returns:
None- No data returned
executeCommand#
(Script only) Executes given integration command / script and arguments
Arguments:
commandstr - Integration command name or script name to runargsdict - Integration command / script arguments
Returns:
Union[dict, list]: Command execution response wrapped in Demisto entry object
executeCommandBatch#
(Script only) Execute list of commands in the following format {"command_name":args}
Example:
[{"get-endpoint-data":{"endpoint_hostname":"example"}}, {"get-user-data":{"user_email":"example@gmail.com"}}]
Arguments:
commands_listlist[dict[str,any]] - list of dicts each represent a command.
Returns:
list[Union[dict, list]]: list of the Command execution response wrapped in Demisto entry object.
findUser#
(Integration only) Looks up for a user in the system
Arguments:
usernamestr - The username of the user to search for (Default value = None)emailstr - The email address of the user to search for (Default value = None)
Returns:
dict- Object representing the user found
get#
Extracts field value from nested object
Arguments:
objdict - The object to extract the field fromfieldstr - The field to extract from the object, given in dot notationdefaultParamobject - The default value to return in case the field doesn't exist in obj
Returns:
str- The value of the extracted field
getAllSupportedCommands#
(Script only) Retrieves all available integration commands and scripts
Returns:
dict- Object of all available integrations and scripts
getArg#
Extracts given argument from the arguments object
Arguments:
argstr - Argument to get value of
Returns:
str- Argument value
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#
Retrieves file path and name, given file entry ID
Arguments:
idstr - File entry ID to get details of
Returns:
dict- Object contains file ID, path and name
getIndexHash#
(Integration only) Retrieves the hashed value of the tenant in which ran in
Returns:
str- Hashed value of tenant name
getIntegrationContext#
(Integration only) Retrieves the IntegrationContext object
Returns:
dict- IntegrationContext object
getIntegrationContextVersioned#
(Integration only) Retrieves the versioned IntegrationContext object
Arguments:
refreshbool - 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#
(Integration only) Retrieves the LastMirrorRun object
Returns:
dict- LastMirrorRun object
getLastRun#
(Integration only) Retrieves the LastRun object
Returns:
dict- LastRun object
getLicenseCustomField#
Get a custom field from content XSOAR configuration (can only be run in system integrations)
Arguments:
keystr - The key name inside the content object to search for.
Returns:
str- the value stored in content object that matced the given key.
getLicenseID#
Retrieves the ID of the license used in the server
Returns:
str- The license ID
getParam#
(Integration only) Extracts given parameter from the integration parameters object
Arguments:
paramstr - Integration parameter to get value of
Returns:
str- Integration parameter value
gets#
Extracts field value from nested object
Arguments:
objdict - The object to extract the field fromfieldstr - The field to extract from the object, given in dot notation
Returns:
str- The value of the extracted field
handleEntitlementForUser#
(Integration only) Sends request to server to process entitlement response given from messaging client
Arguments:
incidentIDstr - The incident ID in which the question was sent inguidstr - The entitlement UUID which identifies the questionemailstr - The email address of the user that respondedcontentstr - The content of the responsetaskIDstr - The playbook task ID to mark as complete (Default value = "")
Returns:
None- No data returned
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#
In script, retrieves the Incidents list from the context
In integration, used to return incidents to the server.
Arguments:
incidentslist - In integration only, list of incident objects (Default value = None).
Returns:
list- List containing the current incident object.
info#
Prints a message to the server logs in info level
Arguments:
msgstr - The message to be loggedargsdict - Additional arguments to log
Returns:
None- No data returned
initialize#
Runs some initializations to the demisto object. Should not be used in integration code
integrationInstance#
(Integration only) Retrieves the integration instance name in which ran in
Returns:
str- The integration instance name
internalHttpRequest#
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:
methodstr - HTTP method such as: GET or POSTuristr - 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#
Retrieves the ID of the investigation in which being run in
Returns:
dict- Object contains the investigation ID
isTimeSensitive#
This function will indicate whether the command reputation (auto-enrichment) is called as auto-extract=inline. So for default the function return False.
log#
Prints a message to the current incidents war room log
Arguments:
msgstr - The message to be logged
Returns:
None- No data returned
mapObject#
Mapping an object using chosen mapper
Returns:
dict- the obj after mapping
mirrorInvestigation#
(Integration only) Marks an investigation as mirrored
Arguments:
idstr - Incident ID to mirrormirrorTypestr - Contains mirror type and mirror direction separated by colon, e.g. all:bothautoClosebool - Whether to close the investigation when the mirrored channel is closed/archived (Default value = False)
Returns:
None- No data returned
params#
(Integration only) Retrieves the integration parameters object
Returns:
dict- Integrations parameters object
parentEntry#
Retrieves information regarding the war room entry from which the method runs
Returns:
dict- information regarding the current war room entry
results#
Outputs entries to the war-room
Arguments:
resultsUnion[list, dict] - The entry object or array of entry objects to output
Returns:
None- No data returnedAn example of results argument:
searchIndicators#
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:
fromdatestr - The start date to search from (Default value = '')querystr - Indicator search query (Default value = '')sizeint - Limit the number of returned results (Default value = 100)pageint - Response paging (Default value = 0)todatestr - The end date to search until to (Default value = '')valuestr - The indicator value to search (Default value = '')searchAfterlist - Use the last searchIndicators() outputs for search batch (Default value = None)populateFieldsstr - Comma separated fields to filter (e.g. "value,type")
Returns:
dict- Object contains the search resultsYou 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
You can then use the returned value of searchAfter to iterate over all batches.
searchRelationships#
Retrieves Indicators Relationship data according to given filters.
Arguments:
argsdict - 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):
setAssetsLastRun#
(Integration only) Stores given object in the AssetsLastRun object
Arguments:
objdict - The object to store
Returns:
None- No data returned
setContext#
(Script only) Sets given value in path in the context data
Arguments:
contextPathstr - The context data path to set the value invaluestr - The value to set in the context data path
Returns:
dict- Object contains operation result status
setIntegrationContext#
(Integration only) Stores given object in the IntegrationContext object
Arguments:
contextdict - The object to store
Returns:
None- No data returned
setIntegrationContextVersioned#
(Integration only) Stores given object in the IntegrationContext object in given version
Arguments:
contextdict - The object to storeversionint - The context version to set. If the version is older than the current, an error will be thrown. (Default value = -1) # noqasyncbool - 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#
(Integration only) Stores given object in the LastMirrorRun object
Arguments:
objdict - The object to store
Returns:
None- No data returned
setLastRun#
(Integration only) Stores given object in the LastRun object
Arguments:
objdict - The object to store
Returns:
None- No data returned
uniqueFile#
Generate a unique file name based upon a random UUID
Returns:
str- Random UUID
updateModuleHealth#
(Integration only) Updated integration module health with given message
Arguments:
dataUnion[str, dict] - Either the message to display in the integration module health, or a dictionary containing the "eventsPulled" field (number).is_errorbool - Whether or not to display it as an error message in the fetch history.
Returns:
None- No data returned