pysros - Model-driven SR OS interface

Library for management of Nokia SR OS nodes.

pysros.management - Connection and data handling

This module contains basic primitives for managing an SR OS node. It contains functions to obtain and manipulate configuration and state data.

pysros.management.connect(*, host, port=830, username, password=None, yang_directory=None, rebuild=False, transport='netconf', timeout=300)

Create a Connection object. This function is the main entry point for model-driven management of configuration and state for a specific SR OS node using the pySROS library.

Note

All parameters to connect are ignored when executed on an SR OS node.

Parameters
  • host (str) – Hostname, Fully Qualified Domain Name (FQDN) or IP address of the SR OS node.

  • port (int, optional) – TCP port on the SR OS node to connect to. Default 830.

  • username (str) – User name.

  • password (str, optional) – User password. If the password is not provided the systems SSH key will be used.

  • yang_directory (str, optional) – Path (absolute or relative to the local machine) to the YANG modules for the specific node. If this argument is used, YANG modules are not downloaded from the SR OS node.

  • rebuild (bool, optional) – Trigger the rebuild of an already cached YANG schema.

  • timeout (int, optional) – Timeout of the transport protocol in seconds. Default 300.

Returns

Connection object for specific SR OS node.

Return type

Connection

Raises
  • RuntimeError – Error occurred during creation of connection

  • ModelProcessingError – Error occurred during compilation of the YANG modules

Note

When executing a Python application using the pySROS libraries on a remote workstation, the initial connection is slower to complete than subsequent connections as the schema is generated from the YANG models and cached.

Example 1 - Connection using YANG models automatically obtained from the SR OS node
from pysros.management import connect
from pysros.exceptions import ModelProcessingError
import sys

def get_connection():
    try:
        connection_object = connect(host="192.168.74.51",
                                    username="admin",
                                    password="admin")
    except RuntimeError as runtime_error:
        print("Failed to connect.  Error:", runtime_error)
        sys.exit(-1)
    except ModelProcessingError as model_proc_error:
        print("Failed to create model-driven schema.  Error:", model_proc_error)
        sys.exit(-2)
    return connection_object

if __name__ == "__main__":
    connection_object = get_connection()
Example 2 - Connection using YANG models obtained from a local directory
from pysros.management import connect
from pysros.exceptions import ModelProcessingError
import sys

def get_connection():
    try:
        connection_object = connect(host="192.168.74.51",
                                    username="admin",
                                    password="admin",
                                    yang_directory="./YANG")
    except RuntimeError as runtime_error:
        print("Failed to connect.  Error:", runtime_error)
        sys.exit(-1)
    except ModelProcessingError as model_proc_error:
        print("Failed to create model-driven schema.  Error:", model_proc_error)
        sys.exit(-2)
    return connection_object

if __name__ == "__main__":
    connection_object = get_connection()
pysros.management.sros()

Determine whether the execution environment is an SR OS node

Returns

True if the application is executed on an SR OS node, False otherwise.

Return type

bool

Example
from pysros.management import sros

def main():
    if sros():
        print("I'm running on a SR OS device")
    else:
        print("I'm not running on a SR OS device")

if __name__ == "__main__":
    main()
class pysros.management.Connection(*args, yang_directory, rebuild, **kwargs)

Bases: object

An object representing a connection to an SR OS device. This object is transport agnostic and manages the connection whether the application is run on the SR OS node or remotely.

Warning

You should not create this class directly. Please use connect() instead.

The underlying transport is NETCONF when executed on a machine that is not running SR OS.

Variables
disconnect()

Disconnect the current transport session. After disconnect, the model-driven interfaces for the SR OS devices are not available.

Example
from pysros.management import connect
connection_object = connect()
connection_object.disconnect()
cli(command)

Run a single MD-CLI command. A single line of input is allowed. This may include MD-CLI output redirection (such as no-more). Some restrictions apply to the commands that may be provided.

Parameters

command (str) – MD-CLI command

Returns

Output as returned from the MD-CLI. The returned data is an unstructured string. An empty string is returned if the command does not have any output (for example, a clear command).

Return type

str

Raises
Example
from pysros.management import connect
connection_object = connect(host='192.168.1.1', username='admin', password='admin')
print(connection_object.cli('show version'))
class pysros.management.Datastore(connection, target)

Bases: object

Datastore object that can be used to perform multiple operations on a specified datastore.

get(path, *, defaults=False, config_only=False)

Obtain a pySROS data structure containing the contents of the supplied path. See the The pySROS data model section for more information about the pySROS data structure.

Parameters
  • path (str) – Path to the requested node in the datastore. The path is an instance-identifier based on RFC 6020 and RFC 7951. The path can be obtained from an SR OS device using the pwc json-instance-path MD-CLI command. The path may point to a YANG Container, List, Leaf, Leaf-List or a specific List entry.

  • defaults (bool) – Obtain default values in addition to specifically set values.

  • config_only (bool) – Obtain configuration data only. Items marked as config false in YANG are not returned.

Returns

A pySROS data structure. This may be a simple value or a more complicated structure depending on the path requested.

Return type

pysros.wrappers.Leaf, pysros.wrappers.LeafList, pysros.wrappers.Container

Raises
  • RuntimeError – Error if the connection was lost.

  • InvalidPathError – Error if the path is malformed.

  • SrosMgmtError – Error for broader SR OS issues including (non-exhaustive list): passing invalid objects, and setting to an unsupported branch.

  • TypeError – Error if fields or keys are incorrect.

  • InternalError – Error if the schema is corrupted.

Example
from pysros.management import connect
import sys
connection_object = connect()
try:
    oper_name = connection_object.running.get("/nokia-state:state/system/oper-name")
except RuntimeError as runtime_error:
    print("Runtime Error:", runtime_error)
    sys.exit(100)
except InvalidPathError as invalid_path_error:
    print("Invalid Path Error:", invalid_path_error)
    sys.exit(101)
except SrosMgmtError as sros_mgmt_error:
    print("SR OS Management Error:", sros_mgmt_error)
    sys.exit(102)
except TypeError as type_error:
    print("Type Error:", type_error)
    sys.exit(103)
except InternalError as internal_error:
    print("Internal Error:", internal_error)
    sys.exit(104)
set(path, value)

Set a pySROS data structure to the supplied path. See the The pySROS data model section for more information about the pySROS data structure.

Parameters
  • path (str) – Path to the target node in the datastore. See the path parameter definition in pysros.management.Datastore.get() for details.

  • value – Value to set the node to. When path points to a Leaf, the value should be a str (optionally wrapped in a pysros.wrappers.Leaf). When path points to a Leaf-List, the value should be a list of str (optionally wrapped in a pysros.wrappers.LeafList). When path points to a Container or list item, the value should be a dict (optionally wrapped in a pysros.wrappers.Container). Valid nested data structures are supported.

Raises
  • RuntimeError – Error if the connection is lost.

  • InvalidPathError – Error if the path is malformed.

  • SrosMgmtError – Error for broader SR OS issues, including (non-exhaustive list): passing invalid objects, and setting to an unsupported branch.

  • TypeError – Error if fields or keys are incorrect.

  • InternalError – Error if the schema is corrupted.

  • SrosConfigConflictError – Error if configuration commit failed due to conflicts.

Example 1 - Configuring a leaf
from pysros.management import connect

connection_object = connect()
payload = "my-router-name"
connection_object.candidate.set("/nokia-conf:configure/system/name", payload)
Example 2 - Configuring a more complex structure
from pysros.management import connect
from pysros.wrappers import *

connection_object = connect()
path = '/nokia-conf:configure/router[router-name="Base"]/interface[interface-name="demo1"]'
data = Container({'interface-name': Leaf('demo1'), 'port': Leaf('1/1/c1/1:0'),
       'ipv4': Container({'primary': Container({'prefix-length': Leaf(24),
       'address': Leaf('5.5.5.1')})}), 'admin-state': Leaf('enable')})
connection_object.candidate.set(path, data)
delete(path)

Delete a specific path from an SR OS node.

Parameters

path (str) – Path to the node in the datastore. See the path parameter definition in pysros.management.Datastore.get() for details.

Raises
  • RuntimeError – Error if the connection is lost.

  • InvalidPathError – Error if the path is malformed.

  • SrosMgmtError – Error for broader SR OS issues, including (non-exhaustive list): passing invalid objects, and setting to an unsupported branch.

  • TypeError – Error if fields or keys are incorrect.

  • InternalError – Error if the schema is corrupted.

  • SrosConfigConflictError – Error if configuration commit failed due to conflicts.

Example
from pysros.management import connect
connection_object = connect()
connection_object.candidate.delete('/nokia-conf:configure/log/log-id[name="33"]')
exists(path)

Check if a specific node exists.

Parameters

path (str) – Path to the node in the datastore. See the path parameter definition in pysros.management.Datastore.get() for details.

Return type

bool

Raises
  • RuntimeError – Error if the connection is lost.

  • InvalidPathError – Error if the path is malformed.

  • SrosMgmtError – Error for broader SR OS issues, including (non-exhaustive list): passing invalid objects, and setting to an unsupported branch.

  • TypeError – Error if fields or keys are incorrect.

  • InternalError – Error if the schema is corrupted.

Example
from pysros.management import connect
connection_object = connect()
if connection_object.running.exists('/nokia-conf:configure/log/log-id[name="33"]') == True:
    print("The log with the ID of 33 is present on the SR OS router")
else:
    print("This log ID is not present on the SR OS router")
exception pysros.management.SrosMgmtError

Bases: Exception

Exception raised by the pysros.management objects when:

exception pysros.management.InvalidPathError

Bases: Exception

Exception raised when a path provided by the user:

  • is empty

  • fails to parse

  • does not point to an existing object

  • is missing list keys that must be provided

exception pysros.management.ModelProcessingError

Bases: Exception

Exception raised when an error occurs during processing of the YANG model (schema) when:

  • a YANG file cannot be found

  • a YANG file is malformed

exception pysros.management.InternalError

Bases: Exception

Exception raised for broader issues when:

  • schema creation fails and this unfinished schema is utilized

exception pysros.management.SrosConfigConflictError

Bases: Exception

Exception raised when a configuration commit failed due to conflicts between the candidate datastore and the baseline datastore. Retrying the configuration operation usually resolves the situation. If retrying does not resolve the issue, the connection should be closed using pysros.management.Connection.disconnect() and the operation restarted to make a new connection.

exception pysros.management.ActionTerminatedIncompleteError

Bases: Exception

Exception raised when an operation (also known as an action) completes with a terminated-incomplete status.

pysros.management.Empty

Define the YANG Empty type.

pysros.pprint - Specialized output formatting

This module contains functions to assist with stylized formatting of data.

class pysros.pprint.TreePrinter(*, align=False, depth=None)

Bases: object

Object used to print the result of a call to pysros.management.Datastore.get() as an ASCII tree.

Parameters
  • align (bool) – Whether to align values of a container in the same column.

  • depth (None, int) – Maximum tree depth to print.

Raises

ValueError – Error if the depth is not positive.

Note

The pysros.pprint.printTree() function provides a simple way to use this object.

print(obj)

Print the specified object.

Parameters

obj – Object to print.

pysros.pprint.printTree(obj, **kwargs)

Print the result of a call to pysros.management.Datastore.get() as an ASCII tree.

See arguments of TreePrinter

Example
from pysros.pprint import printTree
from pysros.wrappers import Leaf, Container

def main():
    data = Container({'auto-config-save': Leaf(True),
                      'capabilities': Container({'candidate': Leaf(True),
                      'writable-running': Leaf(False)}), 'admin-state': Leaf('enable')})
    printTree(data)

if __name__ == "__main__":
    main()
class pysros.pprint.Column(width, name=None, align='<', padding=0)

Bases: object

Column descriptor to be used in pysros.pprint.Table and pysros.pprint.KeyValueTable.

Parameters
  • width (int) – Width of the column (number of characters).

  • name (None, str) – Name of the column. This may be None when column headers are not to be printed. Default None.

  • align (str) – Alignment of the column: ‘<’ for left, ‘>’ for right and ‘^’ for centered. Defaults to ‘<’.

  • padding (int) – Number of padding characters, already accounted for in width. Default 0.

Raises

ValueError – Error if align is not valid.

format(value)

Format a value according to the parameters of this column, considering width, alignment, and padding.

Parameters

value – Value to format.

Returns

Formatted value.

Return type

str

static create(arg)

Static method to create a Column object.

Parameters

arg (pysros.pprint.Column, tuple) – This can either be a pysros.pprint.Column object or the parameters to pass to the constructor thereof.

Raises

TypeError – Error if Column is not valid.

class pysros.pprint.Padding(width)

Bases: pysros.pprint.Column

Special type of column which takes no data. It is only used to add empty space into a table.

Parameters

width (int) – Width of the (empty) column.

class pysros.pprint.Table(title, columns, width=79, showCount=None, summary=None)

Bases: pysros.pprint.ATable

Class that provides the functionality to display tabulated data in the standard SR OS style.

Parameters
  • title (str) – Title of the table.

  • columns – List of column descriptions. Elements of the list can be a pysros.pprint.Column or a tuple with parameters to be passed to pysros.pprint.Column.create().

  • width (int) – Width of the table in characters.

  • showCount – Indicate if a count of rows should be shown in the footer. In case no count is required, pass in None. In case a count is required, pass in the name of the object represented in a row.

  • summary (str) – Optional block of text to be displayed in the footer.

Example creation of a Table object
from pysros.pprint import Table, Padding

def simple_table_builder_example():
    summary = \
    """
This is the text that we would like in our summary sections
at the end of the output"""
    rows = [["row0col0", "row0col1"], ["row1col0", "row1col1"]]
    cols = [(30, "Column0"), (30, "Column1")]
    width = sum([col[0] for col in cols])
    table = Table("This is my tables title", columns=cols,
                  showCount="CounterName", summary=summary, width=width)
    return table, rows

if __name__ == "__main__":
    table, rows = simple_table_builder_example()
print(rows)

Display a complete table when passed in the rows of data. Separate components are displayed as configured during initialization.

Parameters

rows – List of tuples containing the data to be displayed. Each tuple in the list is a row and each item in the tuple is the value for a specific column. Padding columns do not need corresponding values in the tuple.

Example Table.print() using the Table defined in this Example creation of a Table object
>>> def table_print_example(table, rows):
...     table.print(rows)
...
>>> table_print_example(table, rows)
============================================================
This is my tables title
============================================================
Column0                        Column1
------------------------------------------------------------
row0col0                       row0col1
row1col0                       row1col1
------------------------------------------------------------
No. of CounterName: 2

This is the text that we would like in our summary sections
at the end of the output
============================================================
printRows(rows)

Print rows of data.

Parameters

rows – List of tuples containing the data to be displayed. Each tuple in the list is a row and each item in the tuple is the value for a specific column. Padding columns do not need corresponding values in the tuple.

Example Table.printRows() using the Table defined in this Example creation of a Table object
>>> def table_printRows_example(table, rows):
...     table.printRows(rows)
...
>>> table_printRows_example(table, rows)
row0col0                       row0col1
row1col0                       row1col1
printRow(row)

Print a specific row of data.

Parameters

row – Tuple where each item in the tuple is the value for a specific column. Padding columns do not need corresponding values in the tuple.

Example Table.printRow() using the Table defined in this Example creation of a Table object
>>> def table_printRow_example(table, row):
...     table.printRow(row)
...
>>> table_printRow_example(table, rows[0])
row0col0                       row0col1
printColumnHeaders()

Print the column headers and a separator line.

>>> def table_printColumnHeaders_example(table):
...     table.printColumnHeaders()
...
>>> table_printColumnHeaders_example(table)
Column0                        Column1
------------------------------------------------------------
printSummary(showLine=True, customSummary=None)

Print a summary. This section contains the count of rows and any optional summary text.

Parameters
  • showLine (bool) – Display a line above the summary section.

  • customSummary (str) – Custom text to be displayed.

Example Table.printSummary() using the Table defined in this Example creation of a Table object
>>> def table_printSummary_example(table):
...     table.printSummary(customSummary='This is an optional customized summary')
...
>>> table_printSummary_example(table)
------------------------------------------------------------
No. of CounterName: 0
This is an optional customized summary
class pysros.pprint.KeyValueTable(title, columns, width=79)

Bases: pysros.pprint.ATable

Display a list of key and value data in an SR OS table format.

Parameters
  • title (str) – Title of the table.

  • columns – List of column descriptions. Elements of the list can be pysros.pprint.Column or a tuple with parameters to be passed to pysros.pprint.Column.create(). When displaying the data, key and value columns are interleaved. Multiple key-value pairs are allowed on a single row, and the number of columns is even, that is, key and value data always appear on the same row next to each other.

  • width – Width of the table in characters.

Raises

ValueError – Error if the number of columns is not valid.

Example table creation using KeyValueTable
>>> from pysros.pprint import KeyValueTable
>>> table = KeyValueTable('Key Value Table Title', [(20, None), (20, None)])

Note

This class defines the KeyValueTable object. The KeyValueTable.print(), KeyValueTable.printKV() or KeyValueTable.printKVs() methods should be used to output KeyValueTables.

printKV(*kvs)

Print a table of key-value pairs that are passed into this method. This method does not require the data to be structured as a list of 2-tuples. The key-value pairs are displayed in the available columns if the pairs are available in the KeyValueTable definition.

Parameters

args – Interleaved key and value objects.

Example table output using KeyValueTable and KeyValueTable.printKV().
>>> from pysros.pprint import KeyValueTable
>>> table = KeyValueTable(None, [(20, None), (20, None)])
>>> table.printKV("k0", "v0", "k1", "v1", "k2", "v2")
k0                  : v0
>>> table = KeyValueTable(None, [(12,), (12,), (12,), (12,), (12,), (12,)])
>>> table.printKV("k0", "v0", "k1", "v1", "k2", "v2")
k0          : v0           k1          : v1           k2          : v2
printKVs(items)

Print a table of key-value pairs that are passed into this method as a list of 2-tuples.

Parameters

data – List of tuples containing the data to be displayed. Each tuple in the list must contain two fields: (key, value). Data is spread over the available columns first, starting a new row when required.

Example table output using KeyValueTable and KeyValueTable.printKVs().
>>> from pysros.pprint import KeyValueTable
>>> table = KeyValueTable(None, [(20, None), (20, None)])
>>> table.printKVs([("k0", "v0"), ("k1", "v1"), ("k2", "v2")])
k0                  : v0
k1                  : v1
k2                  : v2
>>> table = KeyValueTable(None, [(12,), (12,), (12,), (12,), (12,), (12,)])
>>> table.printKVs([("k0", "v0"), ("k1", "v1"), ("k2", "v2")])
k0          : v0           k1          : v1           k2          : v2
print(data)

Display a complete table when passed in the list of key-value pairs. Separate components are displayed as configured during initialization.

Parameters

data – List of tuples containing the data to be displayed. Each tuple in the list must contain two fields: (key, value). Data is spread over the available columns first, starting a new row when required.

Example table output using KeyValueTable and KeyValueTable.print().
>>> from pysros.pprint import KeyValueTable
>>> data = [('k0','v0'), ('k1','v1'),('k2','v2')]
>>> table = KeyValueTable('Two column Key Value Table Title', [(20, None), (20, None)])
>>> table.print(data)
===============================================================================
Two column Key Value Table Title
===============================================================================
k0                  : v0
k1                  : v1
k2                  : v2
===============================================================================
>>> table = KeyValueTable('Six column Key Value Table Title',
...                       [(12,), (12,), (12,), (12,), (12,), (12,)])
>>> table.print(data)
===============================================================================
Six column Key Value Table Title
===============================================================================
k0          : v0           k1          : v1           k2          : v2
===============================================================================
printColumnHeaders()

Print the column headers and a separator line.

>>> def table_printColumnHeaders_example(table):
...     table.printColumnHeaders()
...
>>> table_printColumnHeaders_example(table)
Column0                        Column1

pysros.wrappers - Model-driven class wrappers

This module contains wrappers describing the YANG structure and metadata obtained from SR OS.

class pysros.wrappers.Container(value=None)

Bases: pysros.wrappers.Wrapper

YANG container data structure node wrapper.

A YANG container in the pySROS data structure behaves in the same way as a Python dict, where the value of a field can be obtained using the field name.

Variables

data – dictionary containing the fields data

class pysros.wrappers.Leaf(value)

Bases: pysros.wrappers.Wrapper

YANG leaf data structure node wrapper.

Depending on the base (root) YANG type of the node, this object wraps a str, int, or bool.

Variables

data – python object corresponding to the value

class pysros.wrappers.LeafList(value=None)

Bases: pysros.wrappers.Wrapper

YANG leaf-list data structure node wrapper.

A YANG leaf-list in the pySROS data structure behaves in the same way as a Python list, where the separate values can be obtained using an index.

Variables

data – list containing the values

class pysros.wrappers.Schema(module)

Bases: object

Metadata about the YANG schema associated with elements in the data structure.

Note

pysros.wrappers.Schema metadata is read-only.

Variables

module – YANG module name from which this node originates

property module

YANG module name from which this node originates.

pysros.exceptions - pySROS specific exceptions

This module contains exceptions for error handling within pySROS.

exception pysros.exceptions.SrosMgmtError

Bases: Exception

Exception raised by the pysros.management objects when:

exception pysros.exceptions.InvalidPathError

Bases: Exception

Exception raised when a path provided by the user:

  • is empty

  • fails to parse

  • does not point to an existing object

  • is missing list keys that must be provided

exception pysros.exceptions.ModelProcessingError

Bases: Exception

Exception raised when an error occurs during processing of the YANG model (schema) when:

  • a YANG file cannot be found

  • a YANG file is malformed

exception pysros.exceptions.InternalError

Bases: Exception

Exception raised for broader issues when:

  • schema creation fails and this unfinished schema is utilized

exception pysros.exceptions.SrosConfigConflictError

Bases: Exception

Exception raised when a configuration commit failed due to conflicts between the candidate datastore and the baseline datastore. Retrying the configuration operation usually resolves the situation. If retrying does not resolve the issue, the connection should be closed using pysros.management.Connection.disconnect() and the operation restarted to make a new connection.

exception pysros.exceptions.ActionTerminatedIncompleteError

Bases: Exception

Exception raised when an operation (also known as an action) completes with a terminated-incomplete status.

pysros.ehs - Functions for the event handling system (EHS)

The pysros.ehs module provides functionality to obtain data from the specific event that triggered the execution of a Python application from the event handling system (EHS).

Note

This module is available when executing on SR OS only. On a remote machine, the event handling system (EHS) and its functionality are not supported.

pysros.ehs.get_event()

The EHS event that triggered the execution of the Python application.

Returns

The Event object or None.

Return type

pysros.ehs.Event or None

class pysros.ehs.Event

The EHS event Class for the event that triggered the execution of the Python application.

appid

The name of the application that generated the event.

Type

str

eventid

The event ID number of the application.

Type

int

severity

The severity level of the event.

Type

str

subject

The subject or affected object of the event.

Type

str

gentime

The formatted time, in ISO 8601 format, that the event was generated.

type

str

timestamp

The timestamp, in seconds, that the event was generated.

Type

float

eventparameters()

The additional parameters specific to the event that caused the Python application to execute.

Type

pysros.ehs.EventParams

format_msg()

Return a string representation of the SR OS formatted log message.

Returns

SR OS formatted log message.

Return type

str

class pysros.ehs.EventParams

The additional parameters of the specific pysros.ehs.Event. This class is read-only. Specific additional parameters may be accessed using standard Python subscript syntax.

keys()

Obtain the additional parameters names.

Returns

Additional parameters names for the Event.

Return type

tuple(str)

params[key]

Return the value of the parameter key. If the parameter does not exist, a KeyError is raised.