Help us improve your experience.

Let us know what you think.

Do you have time for a two-minute survey?

header-navigation
keyboard_arrow_up
close
keyboard_arrow_left
Automation Scripting User Guide
Table of Contents Expand all
list Table of Contents
file_download PDF
{ "lLangCode": "en", "lName": "English", "lCountryCode": "us", "transcode": "en_US" }
English
keyboard_arrow_right

Declare and Use Command-Line Arguments in Op Scripts

date_range 18-Jan-24

Junos OS op scripts can accept command-line arguments when you invoke the script. You can include declarations in the op script or statements in the configuration that enable a user to see the list of possible arguments when they request context-sensitive help for the op script in the CLI. The script must also include any necessary declarations and code to process those arguments. The following sections detail how to define the arguments and help text and use the arguments in an op script.

Declaring Op Script Command-Line Arguments

There are two ways to define the list of expected op scripts arguments that will be displayed when using context-sensitive help in the CLI:

  • Include declarations in the op script

  • Include statements in the Junos OS configuration

Script-generated and configuration-generated arguments have the same operational impact. The following sections explain how to use the different methods to define the op script arguments and display them in the CLI:

How to Define Arguments in the Op Script

You can declare an op script's expected command-line arguments directly in the Python, SLAX, or XSLT op script.

To declare command-line arguments in Python op scripts:

  1. Declare a global dictionary named arguments.
  2. For each argument, define a name-value pair that maps to the argument name and argument help text.

Python Syntax

content_copy zoom_out_map
# Define arguments dictionary
arguments = {'name1': 'description1', 'name2': 'description2'}

if __name__ == '__main__':
    ...
Note:

To display the arguments in the CLI, Python scripts must include the if __name__ == '__main__': statement.

To declare command-line arguments in SLAX or XSLT op scripts:

  1. Declare a global variable named arguments.
  2. For each argument, define an <argument> element.
  3. Within each <argument> element:
    • Define the <name> element with the name of the argument.
    • Optionally define a <description> element that provides the help text for that argument.

XSLT Syntax

content_copy zoom_out_map
<xsl:variable name="arguments">
    <argument>
        <name>name</name>
        <description>descriptive-text</description>
    </argument>
</xsl:variable>

SLAX Syntax

content_copy zoom_out_map
var $arguments = {
    <argument> {
        <name> "name";
        <description> "descriptive-text";
    }
}

How to Define Arguments in the Junos OS Configuration

You can declare an op script's expected command-line arguments in the Junos OS configuration, as an alternative to declaring the arguments directly in the op script.

To declare command-line arguments in the configuration:

  1. Navigate to the arguments statement at the [edit system scripts op file filename] hierarchy level for the given script.
  2. Configure the argument name.
  3. Optionally configure the description statement to provide the help text for the argument.

For example:

content_copy zoom_out_map
[edit system scripts op op file file filename]
arguments {
    argument-name {
        description descriptive-text;
    }
}

How to Display Arguments in the Context-Sensitive Help

After you declare arguments in either the op script or the configuration, you can use the CLI's context-sensitive help to list the op script arguments. If you include the optional argument description, the CLI displays the help text with the argument name.

content_copy zoom_out_map
user@host> op filename ?
Possible completions:
  argument-name        description
  argument-name        description

You can also create a hidden argument for an op script by not including the argument declaration in the op script or the configuration. You use the argument as you normally would in the script, but the CLI does not display the argument or help text when you request context-sensitive help for that op script.

Note:

If you configure command-line arguments in the Junos OS configuration and also declare arguments directly in the op script, the arguments that you declare in the script are still available, but the CLI does not list them under Possible completions when you issue the op filename ? command. This occurs because the management (mgd) process populates the list by first checking the configuration for arguments. The mgd process checks the script for arguments only if no arguments are found in the configuration. Thus, if you declare arguments in the configuration, any arguments declared in the script become hidden in the CLI.

For more information about configuring help text for op scripts, see Configure Help Text for Op Scripts.

Using Command-Line Arguments in Op Scripts

You execute local op scripts with the op filename command. To pass command-line arguments to the script, include each argument name and value when you execute the script.

content_copy zoom_out_map
user@host> op filename argument-name argument-value
Note:

If you specify an argument that the script does not recognize, the script ignores the argument.

The following sections discuss how to use the command-line arguments that are passed to Python, SLAX, and XSLT op scripts:

How to Use Arguments in Python Op Scripts

Python op scripts can use standard command-line parsing libraries to process and use command-line arguments. For example, you can use the Python argparse library to easily define required and optional arguments, specify default values, and handle the arguments in the script.

To enable users to more easily use the standard Python libraries to parse command-line arguments, we modified the way that the arguments are passed to Python op scripts. Starting in Junos OS Release 21.2R1 and Junos OS Evolved Release 21.2R1, when the device passes command-line arguments to a Python op script, it prefixes a single hyphen (-) to single-character argument names and prefixes two hyphens (--) to multi-character argument names. In earlier releases, the devices prefixes a single hyphen (-) to all argument names. You should ensure that your op script properly handles the arguments for your specific release.

The following examples use the argparse module to handle the script arguments. The examples define the global arguments dictionary, and the dictionary keys are used to define the expected arguments for the parser. We provide two example scripts, which appropriately handle the arguments in the specified releases.

Python Syntax (Junos OS Release 21.2R1 or later)

content_copy zoom_out_map
# Junos OS Release 21.2R1 and later
import argparse

arguments = {'arg1': 'description1', 'arg2': 'description2', 's': 'short option'}

def main():
    parser = argparse.ArgumentParser(description='This is a demo script.')

    # Define the arguments accepted by parser
    #  which use the key names defined in the arguments dictionary
    for key in arguments:
        if len(key) == 1:
            parser.add_argument(('-' + key), required=True, help=arguments[key])
        else:
            parser.add_argument(('--' + key), required=True, help=arguments[key])
    args = parser.parse_args()

    # Extract the value
    print (args.arg1)
    print (args.arg2)
    print (args.s)

if __name__ == '__main__':
    main()

Python Syntax (Junos OS Release 21.1 and earlier)

content_copy zoom_out_map
# Junos OS Release 21.1 and earlier
import argparse

arguments = {'arg1': 'description1', 'arg2': 'description2', 's': 'short option'}

def main():
    parser = argparse.ArgumentParser(description='This is a demo script.')

    # Define the arguments accepted by parser
    #  which use the key names defined in the arguments dictionary
    for key in arguments:
        parser.add_argument(('-' + key), required=True, help=arguments[key])
    args = parser.parse_args()

    # Extract the value
    print (args.arg1)
    print (args.arg2)
    print (args.s)

if __name__ == '__main__':
    main()

How to Use Arguments in SLAX and XSLT Op Scripts

To use command-line arguments in SLAX or XSLT op scripts, you must:

  1. Include a parameter declaration for each argument
  2. Ensure the parameter name is identical to the name that you defined in either the arguments variable declaration in the script or the arguments statement in the Junos OS configuration.

XSLT Syntax

content_copy zoom_out_map
<xsl:param name="name"/>

SLAX Syntax

content_copy zoom_out_map
param $name;

The op script assigns the value for each script argument to the corresponding parameter, which can then be referenced throughout the script.

Example: Declaring Arguments in XSLT Op Scripts

Declare two arguments named interface and protocol. Execute the script, specifying the ge-0/2/0.0 interface and the inet protocol as values for the arguments.

The following examples show how to declare the arguments in either the XSLT script or the configuration:

Declaring Arguments in the Op Script (script1)

content_copy zoom_out_map
<xsl:variable name="arguments">
    <argument>
        <name>interface</name>
        <description>Name of interface to display</description>
    </argument>
    <argument>
        <name>protocol</name>
        <description>Protocol to display (inet, inet6)</description>
    </argument>
</xsl:variable>

Declaring Arguments in the Configuration

content_copy zoom_out_map
[edit system scripts op]
file script1 {
    arguments {
        interface {
            description "Name of interface to display";
        }
        protocol {
            description "Protocol to display (inet, inet6)";
        }
    }
}

In addition to declaring the arguments in the script or the configuration, you must also declare the corresponding parameters in the script in order to reference the script arguments and access their values.

Declaring the Parameters

content_copy zoom_out_map
<xsl:param name="interface"/>
<xsl:param name="protocol"/>

Provide the argument names and values when you execute the script. For example:

Executing the Script

content_copy zoom_out_map
user@host> op script1 interface ge-0/2/0.0 protocol inet

Example: Declaring and Using Arguments in Python Op Scripts

Declare two arguments named interface and p in the Python op script. Execute the script, specifying the ge-0/2/0.0 interface and the inet protocol as values for the arguments. Select the appropriate argument handling statements based on your release. The script uses statements compatible with Junos OS Release 21.2R1 and later and comments out the statements for handling arguments in older releases.

Declaring Arguments in the Op Script (script1.py)

content_copy zoom_out_map
from jnpr.junos import Device
import argparse

# Define arguments dictionary
arguments = {'interface': 'Name of interface to display', 'p': 'Protocol to display (inet, inet6)'}

def main():

    parser = argparse.ArgumentParser()

    # Argument handling for Junos OS Release 21.2R1 or later 
    for key in arguments:
        if len(key) == 1:
            parser.add_argument(('-' + key), required=True, help=arguments[key])
        else:
            parser.add_argument(('--' + key), required=True, help=arguments[key])

    # Argument handling for Junos OS Release 21.1 and earlier 
    #for key in arguments:
    #    parser.add_argument(('-' + key), required=True, help=arguments[key])

    args = parser.parse_args()

    try:
        with Device() as dev:

            res = dev.rpc.get_interface_information( 
                interface_name=args.interface, terse=True, normalize=True)
            if (res.find("logical-interface/oper-status") is not None):
                print (args.interface + " status: " + 
                    res.findtext("logical-interface/oper-status"))

            for elem in res.xpath("//address-family \
                [normalize-space(address-family-name)=$protocol]", 
                protocol=args.p):
                if (elem.find("interface-address/ifa-local") is not None):
                    print ("inet address: " + 
                    elem.find("interface-address/ifa-local").text)

    except Exception as err:
        print (err)

if __name__ == '__main__':
    main()

Alternatively, instead of including the arguments dictionary in the Python op script, you can include the arguments in the configuration exactly as you would for SLAX and XSLT scripts.

To view the op script arguments in the CLI's context-sensitive help, issue the op filename ? command.

Displaying the Arguments

content_copy zoom_out_map
user@host> op script1.py ?
Possible completions:
  <[Enter]>            Execute this command
  <name>               Argument name
  detail               Display detailed output
  interface            Name of interface to display
  invoke-debugger      Invoke script in debugger mode
  p                    Protocol to display (inet, inet6)
  |                    Pipe through a command

Provide the argument names and values when you execute the script. For example:

Executing the Script

content_copy zoom_out_map
user@host> op script1.py interface ge-0/2/0.0 p inet
ge-0/2/0.0 status: up
inet address 198.51.100.1/24

Change History Table

Feature support is determined by the platform and release you are using. Use Feature Explorer to determine if a feature is supported on your platform.

Release
Description
21.2R1 and 21.2R1-EVO
Starting in Junos OS Release 21.2R1 and Junos OS Evolved Release 21.2R1, when the device passes command-line arguments to a Python op script, it prefixes a single hyphen (-) to single-character argument names and prefixes two hyphens (--) to multi-character argument names.
footer-navigation