pysros package

Library for management of Nokia SR OS nodes.

pysros.management module

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, 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

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) – User password.

  • 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 *
import sys

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

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

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

if __name__ == "__main__":
    c = 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
c = connect()
c.disconnect()
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
c = connect()
current_operational_name = c.running.get("/nokia-state:state/system/oper-name")
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 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.

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

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

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

c = 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')})
c.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 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.

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

Example
from pysros.management import connect
c = connect()
c.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 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
c = connect()
if c.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.

pysros.management.Empty

Define the YANG Empty type.

pysros.pprint module

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 module

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 module

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.