Scripting guide

Updated at:

A script consists of Python code. The script must define a function with the same name as the template. This function serves as the entry point for task execution.

Code restrictions

  • Do not use the built-in print or while functions.

  • The range function is limited to a maximum value of 1000.

  • Whitelist for import statements:

    • re

    • json

    • time

    • datetime

    • IPy

    • hashlib

    • base64

    • uuid.uuid4

    • difflib

    • ipaddress

    • copy

    • random

    • math

    • string

  • Do not use variables or functions that start with an underscore (_).

Built-in function descriptions

  • logger

    • logger is an instance of the standard logging.Logger module.

    • The following example shows how to output logs. All logs are recorded in the database and can be queried on the task management page.

def logger_example():
    logger.error("an error message")
    logger.warn("a warning message")
    logger.info("an info message")
    logger.debug("a debug message")
  • login_device/device_login

    • login_device/device_login handles device logon and logoff and ensures that device operations are serialized.

  • exec_cli

    • exec_cli sends commands to a device. It can only be used in functions that have the login_device decorator.

    • Parameters:

      • command: string|list. The command or list of commands to send to the device.

      • timeout: int. The default value is 65 s. This is the timeout period for the system to wait for a device response. A Timeout exception is thrown if the device does not respond within the specified time.

      • style: string. Controls the structure of the returned content.

        • simple: Returns the echo content after the input command and terminal prompt are removed.

        • tuple: Splits the echo content and returns a list of (command, output) tuples.

        • verbose: Default value. Returns the raw device echo content.

        • strict: boolean. The default value is True. Specifies whether to check the echo content for exception keywords. If a keyword is found, a SYSTEM_BUSY or BAD_DEVICE_RESPONSE exception is thrown. The keywords include the following:

          • System is busy

          • Permission denied

          • syntax error

          • Unrecognized command

          • Invalid command

          • Invalid parameter

          • at '^' marker

          • Unknown command

          • at '^' position

          • Incomplete command

          • unknown command

          • Operation failed

          • error: configuration database locked by

          • TCAM region is not configured

          • Invalid input

          • Request denied

          • Authorization denied

          • error: commit failed

          • Unavailable command

          • Cannot apply ACL

  • exec_script

    • exec_script calls other templates.

def exec_script_example(target, cli):
    # Call the exec_cli_example device template
    return exec_script('exec_cli_example', _target=target, cli=cli)
  • exec_script_async

    • exec_script_async invokes templates asynchronously.

def exec_script_async_example(target, cli):
    # Asynchronously call the exec_cli_example device template
    task =  exec_script('exec_cli_example', _target=target, cli=cli)
    # Get the result of the asynchronous task
    result = task.get()
    return result
  • current_device

    • current_device returns the currently logged-on device.

@login_device
def get_device():
    device = current_device()
    device['ip']  # Device IP
    device['hostname'] # Hostname 
    device['domain'] # Security domain
    device['space'] # Physical space
    device['status'] # Status
    device['role'] # Role
    device['vendor'] # Vendor
    device['model'] # Model
    device['sn'] # SN
    device['device_id'] # id
  • abort

    • abort stops task execution.

    • When you run the following sample code, the task fails and returns {"message": "xxx", "traceback": [[ "__shadow_{script_MD5_hash}_abort_example_{version_ID}__",2,"abort_example",null]], "error_code": "OZ_USER_ABORT"}.

def abort_example():
    abort("xxx")
  • get_exc_code

    • When you catch an exception, use this function to retrieve the error code.

  • get_traceback

    • When you catch an exception, use this function to retrieve the error stack.

def exc_example():
    try:
        abort("xxx")
    except Exception as e:
        e.message # Returns "xxx"
        get_exc_code(e) # Returns "OZ_USER_ABORT"
        get_traceback() # Returns [["__shadow_{script_MD5_hash}_{template_name}_{version_ID}__",
                        #     {line_number_of_exception},
                        #     {function_name_with_exception},
                        #     null]]

Input parameters

  • By default, the first parameter of a device template is _target. This parameter is a string and can be the device ID, hostname, or IP address.

Output parameters

  • This is used to edit the steps of a change plan.

Code format requirements

  • Code formatting requirements for automation templates.

    • For example, in a user template named example_template, all code must be inside the example_template function. If you reference other functions at the same level, you must declare them as global.

    • re, json, time, and datetime are built-in. You do not need to write import statements for them.

      • Correct example

def func_a():
    pass

def example_template():
    import xxx
    global func_a
    
    def func_b():
        pass
    
    func_a()
    func_b()
  • Code format requirements for inspection templates.

    • An inspection template can contain only one executable function.