• Edge DX Scripting Guide

    Contents

    Introduction

    The Edge DX scripting engine is a powerful and infinitely extensible way to distribute and run scripts on Windows, Linux and Mac devices to perform IT administration tasks and to collect results and data.

    To read about Edge DX features and capabilities, see Welcome to Edge DX.

    Note: The terms SIP and SIP Agent in the UI, scripts and script logs refer to Edge DX. 

    You can see the list of the existing scripts in your tenant in the Configuration > Scripts view:

    edge_config_scripts_main.png

    If you click on a script name, you see all available content fields and options for that script.

    Targeting and Distribution

    Scripts are distributed to all endpoints based on platform – all Windows scripts go to all Windows devices, Linux scripts to Linux devices, and Mac scripts to Mac devices.

    When script settings are changed, they are updated and securely cached on each device when it next does a configuration update, as determined by the Configuration Update interval in Agent Settings. At that time, any new or changed scripts are downloaded by the device and cached locally in a secured folder. Any old or unrecognized files in that folder are removed.

    Script Content Fields

    Click the Add Script button in the top right corner to add a script and configure the script options:

    edge_config_scripts_add_script.png

    Name. A friendly name for the script that is used in the Scripts view, and in the Configuration > System Events and Devices > Device Events views. When the script is cached as a file on the device (in a secured folder), this name is not used, and a random sequence of characters is used as the file name. Most events list both the friendly name and the random file name to ease understanding of which script produced the event.

    Description. Only used as a friendly reminder of what the script does and how to use it.

    Content. A raw text field. Copy and paste to and from a script editor to run, test and develop your script and then copy it here for distribution to devices. Remember that scripts often run in System context (see below) and so might behave differently from when they are run by a user in a script editor.

    Script Options

    Platform

    This determines which device platforms the script is distributed to, and which options are available under Language/Interpreter and Trigger.

    egde_config_scripts_options_platform.png

    Language/Interpreter

    This represents the supported script languages and interpreter on the selected platform. Each script is saved as a local file in a secured folder, and then passed to the selected interpreter on a command line and run in a separate process.

    edge_config_scripts_options_language_interpreter.png

    Trigger

    The list of triggers available for the platform. See the Script Triggers section for more detail.

    Timeout

    The process that runs the script is given a finite time to execute, and then killed if it has hung. If the script completes before timeout then stdout (standard output) and stderr (standard error) results are checked. If there are no errors the stdout text is scanned for data and event results (see below).

    Note: If timeout is set to 0 (zero) then the script is started in a fire-and-forget manner and is not killed if it hangs, no stdout or stderr results are collected, and no data is sent to the Edge DX service.

    Data Collection

    If the Sends Data option is selected and the script completes before the timeout with no errors (empty stderr), then the stdout is inspected for a section that looks like:

    ### SIP DATA BEGINS ###
    [{"ip_address":"192.168.137.16","hostname":"test test.jar.local"}]
    ### SIP DATA ENDS ###

    The data between the “### SIP DATA BEGINS/ENDS ###” lines is a JSON-formatted array of dictionaries that contains rows for the selected index. Examples of how to create this output with PowerShell, Python and other script languages are included in the scripts in your tenant. Any errors in the format are rejected by the Edge DX agent and the reason captured in the Events view.

    edge_config_scripts_data_collection.png

    When the Edge DX agent finds output that matches this pattern, it is sent to the Edge DX service for the specified Data Index, where it can be inspected with the Data view, or in a report if one exists.

    Note: If the Data Index does not already exist, a new one is dynamically created.

    edge_data_create_custom_report.png

    When adding data to a custom index, we strongly recommend using only integer and not floating-point values. For example: It is better to store milliseconds as 375ms, than as 0.375 seconds. This avoids issues with data that spans multiple time periods.

    The Overwrite Existing Data option determines whether the data output appends new rows or overwrites existing data for that device. Reports that show only the most recent status of the device should overwrite existing data, whereas reports that keep a historical log of device activity should not overwrite existing data.

    Whether or not the Sends Data option is selected, the stdout from the script is also inspected for a section like:

    ### SIP EVENT BEGINS ###
    Memory block size: 134217728 Total online memory: 8589934592 Total offline memory: 0
    ### SIP EVENT ENDS ###

    If this is found, then then a System Event is created with the Title containing the script name, and the Description contains the output, like this:

    edge_config_system_events.png

    Additional Options

    Run Only When Online. If the device is not able to connect to the Edge DX service, then this determines whether the script should run anyway. If the script has the Sends Data box enabled and the device is offline, data output will be cached on the client until the device comes back online.

    edge_config_scripts_additional_options.png

    The Run Only When Online option does not apply to Custom Actions, which run only when the device is online and able to receive actions. 

    Run Only When Idle. The Agent Settings page has settings which determine the CPU level and duration which is required for the device to be considered idle. If a script is triggered to run with this option selected and the device is not idle, then the script does not start. This is useful for scripts that consume a lot of system resources and could impact the user if they are actively working.

    Script Triggers

    edge_config_scripts_options_triggers.png

    There are three types of script triggers:

    Time Intervals

    Short Interval. The timing for this is configured in Agent Settings and is typically set at 180 seconds. In other words, all scripts for this trigger are fired by a timer with an interval of 3 minutes.

    Long Interval. The timing for this is also configured in Agent Settings and is typically 600 seconds (10 minutes).

    Once Per Day. Every 15 minutes (by default) the agent checks each of these scripts to see if it has run in the last 24 hours, and if it has not, then it runs it now. It will retry every 15 minutes until there are no errors and then stores the last-run time. If the script is set to Run Only When Online, it will retry every 15 mins until it is online, and then not run again for 24 hours.

    Device Events

    SIP Service Start. This is run whenever the service SIP Agent starts, or restarts. The service automatically starts when the Operating System is booted. It runs as soon as the agent starts, using scripts cached previously. It does not attempt to download or update scripts first.

    SIP Service Stop. This runs when the agent stops, which occurs when it is upgraded, the device is shutdown or rebooted, or when it is manually stopped. Devices have up to 5 seconds to send data or events to the Edge DX service before the agent exits. Any script process still running continues, but output from the script is lost after 5 seconds.

    Network Change. This trigger fires whenever the network interfaces change, which can happen due to power events, network outages, changes of WiFi Access Point, move from LAN to WLAN, etc. Often there are multiple network change events close together, and so the SIP Agent waits for a second to ensure only the last event fires the trigger.

    Process Started (Windows ONLY). When this trigger is selected a Process Name text field appears for the exe name to be matched (e.g. notepad.exe). Note that some applications relaunch themselves and so you can get two Process Started triggers close together when an application is started. This trigger can run the script in a system or user context (see below). This trigger adds the SID and LogonID of the user that started the process as parameters on the command line so they can be used by the script.

    Logon Complete (Windows ONLY). This trigger fires 15-20 seconds after userinit.exe exits, which is at the end of the Windows logon process. The script can be run as System or as User. This trigger adds the SID and LogonID of the user that started the process as parameters on the command line so they can be used by the script.

    LogonNew Session (Windows ONLY). This trigger fires first in the logon process, immediately after the session is created. It is possible some of the Windows environment will not yet be established. Only the SID is available to scripts.

    LogonExplorer Started (Windows ONLY). This trigger fires as soon as explorer.exe is started during the Windows logon process. The script can be run as System or as User. This trigger adds the SID and LogonID of the user that started the process as parameters on the command line so they can be used by the script.

    Logoff (Windows ONLY). This trigger fires right before the user logs off and has around 4 seconds to complete before the session closes. It can only be run as System because once the logoff has begun, no new processes including scripts can be started in the session. Includes both SID and LogonID.

    Session Lock – Explorer Started (Windows ONLY). Fires when the session display is locked. Includes both SID and LogonID.

    Session Unlock – Explorer Started (Windows ONLY). Fires when the session display is unlocked. Includes both SID and LogonID.

    Session Disconnect – Explorer Started (Windows ONLY). Fires when a session is disconnected (except at logoff). It includes both SID and LogonID.

    Session Reconnect – Explorer Started (Windows ONLY). Fires when an existing session is reconnected. It includes both SID and LogonID.

    Custom Actions

    You can use Custom Actions to trigger scripts. These appear as Actions in each Device page.

    To run a script based on a custom action:

    1. Click on a device name in the Edge DX console. The Dashboard for that device opens.
    2. Click the Actions menu towards the top right. These add a request to the device action queue. The agent runs these scripts immediately when it receives them.
      They can also be triggered by an Alert.

    Note: The Action Check interval can be changed in Agent Settings.

    edge_device_device_drilldown_actions.png

    Run Context

    Scripts run in the context of the System, except on Windows where some triggers have the option of running as User.
    System context means NT AUTHORITY\SYSTEM (i.e. LocalSystem) on Windows, and sudo (i.e. root) on Linux and Mac. On Windows the User SID and LogonID are provided as command line parameters on some triggers, so that scripts that run as System can still carry out operations on specific user data. The User SID is provided in SDDL format (for example: “S-1-5-21-368573210-3773030013-3569538123-1001”). Logon ID is a 64-bit hex string (for example: “0x00092c61”). See the Tips and Tricks section for how to use these.

    On Windows the User context means the user who performed the action, the user that started the process or logged onto the desktop. User scripts are copied to a temporary (secured) location, the user is given permissions to execute them, and then they are deleted when complete.

    Tips and Tricks

    Targeting a script at a specific device
    To ensure a script only runs on certain devices, you can add a line like this at the start (PowerShell example):

    if ($env:COMPUTERNAME -ne "DESKTOP-BVD8EN4") { return; }

    You can also filter by Edge DX device group with the SIPDEVICEGROUP environment variable.

    Popping a dialog to a user (Windows)
    The UserPrompt.exe executable included with the SIP Agent on Windows can be used to display a dialog to the user. Use a line like this in a cmd.exe script. Note the “start /b” at the start means that the script immediately returns after launching UserPrompt.exe, and so you will not get timeout errors if the user does not acknowledge the dialog for a long time. However, you will still get an error if the command line fails.

    start /b "C:\program files\Avacee\sip_agent\UserPrompt.exe" "Hello world!"

    Or like this in PowerShell:

    Start-Process (“C:\program files\Avacee\sip_agent\UserPrompt.exe") -ArgumentList """Hello world!"""

    Creating JSON formatted output

    If you want to send data that can be viewed in a report then you need to format it as data. On Windows this is easily done in PowerShell using a Hashtable (which is very much like a Dictionary):

    $MyData = @{} # initialize a hashtable

    $MyData["field_1"] = 20
    $MyData["field_2"] = 100

    Write-Output("### SIP DATA BEGINS ###")
    Write-Output(ConvertTo-Json $MyData -Compress)
    Write-Output("### SIP DATA ENDS ###")

    Every time this script runs it will send a row for that device with two fields and a value for each, which appear as columns in the table report.
    If you want to send multiple rows from each device in a single data upload, you can use a .NET List collection like this:

    $MyDataList = New-Object 'System.Collections.Generic.List[psobject]'

    foreach ($i in $MyDataCollection)
    {
    $MyData = @{} # initialize a hashtable

    $MyData["field_1"] = 20
    $MyData["field_2"] = $i.Property

    $MyDataList.Add($MyData)
    }

    Write-Output("### SIP DATA BEGINS ###")
    Write-Output(ConvertTo-Json $MyDataList -Compress)
    Write-Output("### SIP DATA ENDS ###")

    This will iterate through $MyDataCollection adding a Hashtable to the List for each entry, which will appear as rows for each device in the report table.

    Choosing cmd.exe or VBScript over PowerShell
    PowerShell is very powerful, but it consumes far more resources than cmd.exe and can be slow when iterating through large amounts of data, especially with complete Where-Object queries. Whenever possible, use cmd.exe or VBScript.

    Sending data to the events log using cmd.exe is very simple. For example:

    @echo off
    echo ### SIP EVENT BEGINS ###
    ping www.google.com
    echo ### SIP EVENT ENDS ###

    Using User SID and Logon ID parameter in scripts
    In this example, a PowerShell script running as System in response to a user event (e.g. a Logon) can look in the user’s HKEY_CURRENT_USER registry hive by opening a path under HKEY_USERS using the User SID, which was passed to the script as the first parameter:

    param ( $UserSID, $LogonID ) # this needs to be the first line

    $hku = [Microsoft.Win32.RegistryKey]::OpenBaseKey([Microsoft.Win32.RegistryHive]::Users, 0)
    $hkcuRunKey = $hku.OpenSubKey(($UserSID + '\SOFTWARE\Microsoft\Windows\CurrentVersion\Run'), $false)

    Avoiding Unicode problems in script data output
    Add this line to PowerShell scripts so that all text output is passed and uploaded to the database using Unicode, which allows all international characters and can be searched with all international characters:

    [Console]::OutputEncoding = [System.Text.Encoding]::UTF8

    Without this line, PowerShell will sometimes try and convert international characters to their closest ASCII equivalent, which can play havoc with data formatting.

    Script Use Case

    Here is a step by step guide to creating a script to get the CPU temperature from Microsoft Windows machines, using a PowerShell script, and then displaying the output data in a custom report:

    1. In Edge DX click Configuration > Scripts > Add Script
      Edge_dx_script_create_script_1.png
    2. Complete the script fields as follows:
      - Name: Get CPU Data
      - Description: (optional)
      - Platform: Microsoft Windows
      - Language/Interpreter: PowerShell
      - Trigger: Short Interval Timer
      - Timeout (s): 60
      - Send Data: Checked
      - Overwrite Existing Data: Checked
      - Content: Since the script is going to gather data, include “Write-Output”.
      - Data Index: cpu_temperature
      The Data Index field defines a new location or table that this data is going to be pushed into. Once created, the Data Index can be found under Configuration > Data:
      Edge_dx_scripts_configuration_data_cpu_temp_2.png
    3. When you complete the script fields, click Create Script or Save to New Script / Update Script.
      Edge_dx_script_create_script_save_to_new_script_update_script_7.png

    To create a custom report showing CPU temperature for your devices:

    1. Go to Configuration > Data.
    2. Under Index, click on cpu_temperature (that you created previously) and then click Create Custom Report.
      Edge_dx_settings_data_cpu_temp_create_custom_report_3.png
    3. Give the report a name and description and check Public if you want the report to be viewed by everyone in your organization. Click Create.
    4. Refresh the page and go to Reports. You will find the report you created under the Custom Reports heading. Click it.
      Edge_dx_reports_custom_reports_cpu_temp_4.png
    5. You can give the columns in your report more reader friendly names by clicking Rename Columns. In this example, columns are changed to Temperature and Device Name.

      Edge_dx_reports_customer_reports_temperature_report_john_rename_columns_5.png
    6. When you are done, click Save Report Layout.
      Edge_dx_reports_customer_reports_temperature_report_john_rename_columns_save_report_layout_6.png

      To learn how to get alerts about a temperature report and other alert types, see the Edge DX Alerts article.