using cortex xsoar automations I want to generate a report on post processing script and…
- User
using cortex xsoar automations I want to generate a report on post processing script and send it through email give me the code.
Assistant
Generating a report on "post-processing scripts" in Cortex XSOAR requires a bit of interpretation, as XSOAR doesn't have a specific "post-processing script" type. Instead, scripts become "post-processing" by how they are used (e.g., in "After Incident Created" automations, or as tasks early in a playbook).
For this solution, I'll provide a script that generates a report on all your automation scripts (Python/JavaScript), including their details. This gives you a comprehensive list from which you can identify your "post-processing" scripts based on their name, description, or tags.
Here's the plan:
-
XSOAR Automation Script (Python): This script will:
- Fetch a list of all automation scripts in your XSOAR instance.
- Extract relevant details (name, description, tags, type, last modified).
- Format these details into an HTML table for a clean report.
- Use the
sendEmailcommand to email the report.
-
How to Use It:
- Create a new automation in XSOAR.
- Paste the Python code.
- Run it manually from the playground or integrate it into a playbook.
Step 1: Create the XSOAR Automation Script
Navigate to Settings > Integrations > Automations and click + New Automation.
- Name:
GenerateAutomationScriptsReport(or similar) - Description: Generates an HTML report of all XSOAR automation scripts and sends it via email.
- Type: Python
- Category: Utilities (or create a new one)
- Code: Paste the following Python code.
import demisto_client import html # For escaping HTML characters in descriptions from CommonServerPython import * # For demisto.executeCommand, demisto.args, return_error, isError def get_scripts_data(): """Fetches all automation scripts from XSOAR.""" try: # The getScripts command returns a list containing a single dictionary # with 'Contents' key holding the list of scripts. res = demisto.executeCommand('getScripts', {}) if isError(res): return_error(f"Failed to fetch scripts: {get_error(res)}") scripts = res[0]['Contents'] return scripts except Exception as e: return_error(f"An error occurred while fetching scripts: {e}") def generate_html_report(scripts): """Generates an HTML table report from the list of scripts.""" if not scripts: return "<p>No automation scripts found to report on.</p>" html_content = """ <h2>Cortex XSOAR Automation Scripts Report</h2> <p>This report lists all automation scripts configured in your Cortex XSOAR instance.</p> <table border="1" cellpadding="5" cellspacing="0" style="width:100%; border-collapse: collapse; font-family: Arial, sans-serif; font-size: 14px;"> <thead> <tr style="background-color:#e0e0e0; text-align: left;"> <th style="padding: 10px;">Name</th> <th style="padding: 10px;">Type</th> <th style="padding: 10px;">Description</th> <th style="padding: 10px;">Tags</th> <th style="padding: 10px;">Last Modified</th> <th style="padding: 10px;">Deprecated</th> </tr> </thead> <tbody> """ # Sort scripts alphabetically by name for better readability sorted_scripts = sorted(scripts, key=lambda s: s.get('name', '').lower()) for script in sorted_scripts: name = script.get('name', 'N/A') script_type = script.get('type', 'N/A') # 'javascript', 'python' description = script.get('description', 'No description provided.') tags = ', '.join(script.get('tags', [])) if script.get('tags') else 'None' modified_timestamp = script.get('modified', None) deprecated = 'Yes' if script.get('deprecated', False) else 'No' # Format timestamp if it's available (XSOAR timestamps are usually milliseconds epoch) modified_str = 'N/A' if isinstance(modified_timestamp, (int, float)): try: modified_str = datetime.fromtimestamp(modified_timestamp / 1000).strftime('%Y-%m-%d %H:%M:%S') except Exception: pass # Keep as is if conversion fails # Escape HTML characters in description to prevent rendering issues in email description = html.escape(description) html_content += f""" <tr> <td style="padding: 10px;"><strong>{name}</strong></td> <td style="padding: 10px;">{script_type.capitalize()}</td> <td style="padding: 10px;">{description}</td> <td style="padding: 10px;">{tags}</td> <td style="padding: 10px;">{modified_str}</td> <td style="padding: 10px;">{deprecated}</td> </tr> """ html_content += """ </tbody> </table> <p>Report generated on: {report_date}</p> """.format(report_date=datetime.now().strftime('%Y-%m-%d %H:%M:%S')) return html_content def main(): try: args = demisto.args() to_email = args.get('toEmailAddress') subject = args.get('subject', 'Cortex XSOAR Automation Scripts Report') if not to_email: return_error("Email address is required to send the report. Please provide it in the 'toEmailAddress' argument.") demisto.results(f"Fetching automation scripts...") scripts_data = get_scripts_data() demisto.results(f"Generating HTML report for {len(scripts_data)} scripts...") report_body = generate_html_report(scripts_data) # Send the email using the built-in sendEmail command demisto.results(f"Sending report to {to_email}...") send_email_result = demisto.executeCommand('sendEmail', { 'to': to_email, 'subject': subject, 'body': report_body, 'htmlBody': 'true' # Essential to render the HTML content }) if isError(send_email_result): return_error(f"Failed to send email: {get_error(send_email_result)}") else: demisto.results(f"Report successfully generated and sent to {to_email}") except Exception as e: return_error(f"An error occurred in main: {e}") if __name__ in ('__main__', '__builtin__', 'builtins'): main()
Step 2: Running the Automation
You have a few options to run this automation:
Option 1: From the XSOAR Playground (for testing)
- Go to Playground.
- Type the command in the command line:
Replace!GenerateAutomationScriptsReport toEmailAddress="your_email@example.com" subject="My XSOAR Automation Scripts Report""your_email@example.com"with the actual email address where you want to receive the report.
Option 2: As a Task in a Playbook
You can integrate this automation into any playbook. This is useful if you want to schedule it, or trigger it based on certain events.
- Open or create a new playbook.
- Add a new task.
- Choose Type: Automation.
- Search for your automation script by name (e.g.,
GenerateAutomationScriptsReport). - In the task's inputs, define:
toEmailAddress:your_email@example.com(use a literal value or a playbook input)subject:XSOAR Automation Scripts Overview(optional, default will be used if omitted)
Option 3: Via Scheduled Job (Scheduler)
If you want this report to be sent periodically (e.g., weekly, monthly):
- Go to Settings > Integrations > Jobs.
- Click + New Job.
- Name:
Scheduled Automation Scripts Report - Playbook: Select a simple playbook that contains only one task:
GenerateAutomationScriptsReport. (You'll need to create a dedicated playbook for this if you haven't already). - Schedule: Define your desired frequency (e.g., once a week, every Monday at 9 AM).
- Inputs: Pass the
toEmailAddressandsubjectarguments to the playbook and then to the automation task.
Explanation of the Code:
get_scripts_data(): This function usesdemisto.executeCommand('getScripts', {})to call the internal XSOAR API command that retrieves all configured scripts. It handles the structure of the command's output (res[0]['Contents']).generate_html_report(scripts):- Iterates through the list of scripts obtained.
- Extracts
name,type,description,tags,modifiedtimestamp, anddeprecatedstatus. - Timestamp Conversion: XSOAR timestamps are often in milliseconds since epoch, so
modified_timestamp / 1000is used fordatetime.fromtimestamp(). - HTML Escaping:
html.escape()is used on the description to prevent any HTML tags within the description from breaking the report's layout or posing a security risk. - Builds an HTML table string dynamically, ensuring proper
border,cellpadding, andcellspacingfor readability in email clients. - Sorts scripts by name for easier navigation.
main():- Retrieves
toEmailAddressandsubjectfrom the automation's arguments (demisto.args()). - Calls
get_scripts_data()to fetch the script list. - Calls
generate_html_report()to create the email body. - Uses
demisto.executeCommand('sendEmail', {...})to send the report. ThehtmlBody: 'true'argument is crucial for the email client to render the HTML correctly. - Includes basic error handling and informational
demisto.results()messages.
- Retrieves
This automation provides a robust and easily adaptable way to get an overview of all your XSOAR automation scripts, which you can then use to identify and manage your "post-processing" logic.
-
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.