cancel
Showing results for 
Search instead for 
Did you mean: 
cancel
5718
Views
15
Helpful
10
Replies

How to send NSO commands from python code

zbaka
Level 1
Level 1

I would like to send nso commands like "show ncs-state version" and get the output from a python code. I can't really find an example, and the guides are only showing how to send commands to the devices themselves.

10 Replies 10

tsiemers1
Spotlight
Spotlight

You can use the api to retrive this info. Below is a python example for restconf to get the ncs-state. 

If you go to the console and run the command you are instersted in with a ' | display keypath' you can get the path to the data.

The python example below will retrive the ncs-state version, you will have to modify it and change url and port, and include your user/password in the headers.

nsouser@labncs# show ncs-state version | display keypath 
/ncs-state/version 4.7.3.1
 

Python example:

import requests

url = "http://<ncs-server.com>:<ncs-port>/restconf/data/ncs-state/version"

payload = ""
headers = {
    'Accept': "*/*",
    'Cache-Control': "no-cache",
    'Host': "<ncs-server>:<ncs-port>",
    'accept-encoding': "gzip, deflate",
    'Connection': "keep-alive",
    'cache-control': "no-cache"
    }

response = requests.request("GET", url, data=payload, headers=headers)

print(response.text)

Response:

<version xmlns="http://tail-f.com/yang/ncs-monitoring"  xmlns:tfnm="http://tail-f.com/yang/ncs-monitoring">4.7.3.1</version>

vleijon
Cisco Employee
Cisco Employee

In addition, if you are on the NSO machine and want to do it through the builtin APIs you can do something like this:

#!/usr/bin/env python

import ncs.maagic as maagic
import ncs.maapi as maapi
import _ncs

with maapi.single_read_trans('admin', 'system', db=_ncs.OPERATIONAL) as m:
    print('Maapi: {}'.format(m.get_elem('/ncs-state/version')))
    root = maagic.get_root(m)
    print('Maagic: {}'.format(root.ncs_state.version))

Which gives this output when I run it:

VLEIJON-M-N1WC:test vleijon$ ./foo.py 
Maapi: 5.1.0.1
Maagic: 5.1.0.1


You can re-use the same transaction for multiple things.

tbjurman
Cisco Employee
Cisco Employee

Since you want to do this from Python why not use the Python API, like this:

import ncs

def get_nso_version():
with ncs.maapi.single_read_trans('someuser', 'somegroup') as trans:
root = ncs.maagic.get_root(trans)
return root.tfnm__ncs_state.version

if __name__ == '__main__':
print(get_nso_version())

Running the script looks like this:

$ python nso_version.py
7.2

 

Thanks for the replies. I would like to have some general guidelines how to do these things as for example a package reload or a service creation/commit is probably can not be done in the above way. I understand the above examples but would like to find some documentation that explains it all.  For example:

root.tfnm__ncs_state.version

I can run it and get the expected result, but still struggling how to find out that I need to use "tfnm__ncs__state".
I mean I am probably missing some kind of documentation or something that should help me with these basic things, but I can't find them.
I would like to have complete control of the NSO from a python script. Thanks!

vleijon
Cisco Employee
Cisco Employee
For a more complete understanding of how to develop for NSO I recommend the NSO development guide – in your nso installation you have a doc directory with the full manuals. The development guide has most of the information needed to understand the development process, and there is also an api guide for the APIs that explain how they work.

You can definitely do everything with Python.

By the way, the document can be a bit long, so it might be nice to look at some videos instead: https://www.youtube.com/channel/UCVMgxfH4h4XyNV8VxSMtgnQ/videos I would suggest in particular this overview from last year https://www.youtube.com/watch?v=dxPO3BxX3IU&t=389s and this slightly older Python overview: https://www.youtube.com/watch?v=zrM2vHj6-ZM.

Hopefully this is a good start!

Thanks, I will check the videos, but meanwhile just to be more specific. My main issue is that I feel I ask really basic questions, but still the answer is not in the development guide either. For example if I want to reload packages from a python script like this:

with ncs.maapi.single_write_trans('admin', 'python') as trans:    
root = ncs.maagic.get_root(trans) result = root.ncs__packages.reload() trans.apply()

 

I got the following error:

external error (19): Must exit from configure mode first

This error only happens if there is a new package to be loaded.

If I use maapi.single_read_trans instead I can see in the NSO cli that the upgrade actually starts but then got cancelled:

admin@ncs#
>>> System upgrade is starting.
>>> Sessions in configure mode must exit to operational mode.
>>> No configuration changes can be performed until upgrade has completed.
>>> System upgrade has been cancelled.

And I have also the same(?) error:

external error (19)

I don't find anything about this error, do you have any advice?
Thanks!

 

vleijon
Cisco Employee
Cisco Employee

First it is important to recognize that there are three different concepts here:

 1. Configuration data, read and written through a configuration transaction.
 2. Operational data, accessed through an operational transaction.
 3. Actions that can be accessed in almost any context.


The call apply is used to apply a transaction, and isn't really needed for actions, unless you also have changes to make.

In this case we are talking about the packages reload action, it is a special action that does schema upgrades. For technical reasons the system does not allow you to have active configuration transactions while doing a schema upgrade, that is what it means by "exit from configure mode" and if you try doing package reload in config mode in the cli you will see a similar message.

 

For your particular problem, this modified code will work, and will print the result as well:

#!/usr/bin/env python

import ncs

with ncs.maapi.single_read_trans('admin', 'system', db=ncs.OPERATIONAL) as m:
    root = ncs.maagic.get_root(m)
    result = root.ncs__packages.reload()
    for r in result.reload_result:
        print('Reload result, package {} - result {}'.format(r.package, r.result))

 

I hope this both helps with this problem and helps clarify the concepts. 

Now I get the following message, the transaction can not be finished because of the python scrip itself.

 

external error (19): Data model upgrade failed due to an open transaction:
[1] admin tcp (python from 127.0.0.1) on since 2019-05-31 08:25:36

jacobcf
Cisco Employee
Cisco Employee

Hi everyone,

I wanted to know which python package to install, to import ncs.

Right now I get

ModuleNotFoundError: No module named 'ncs'

this error

jacobalex
Level 1
Level 1

It seems like you want to send NSO (Cisco Network Services Orchestrator) commands from a Python script and retrieve the output. NSO typically manages network devices and services, so you might want to run commands on those devices using NSO. To accomplish this, you can use the NSO REST API, Python libraries like requests, and the ncs Python module.

Here's a general approach to do this:

  1. Install Required Libraries:

    Ensure you have the requests library installed. You can install it using pip:

 

pip install requests

 

  1. Access NSO REST API:

    NSO provides a REST API that you can use to send commands and retrieve the output. You'll need to know the API endpoint URL for your NSO instance. This might look something like: http://nso-server:8080/jsonrpc.

  2. Python Script:

    Here's a Python script that demonstrates how to send an NSO command and retrieve the output:

 

import requests
from requests.auth import HTTPBasicAuth

# Define your NSO server URL and credentials
nso_url = "http://nso-server:8080/jsonrpc"
username = "your_username"
password = "your_password"

# Define the NSO command you want to run
nso_command = {
    "jsonrpc": "2.0",
    "method": "cli",
    "params": {
        "command": "show ncs-state version"
    },
    "id": 1
}

try:
    # Send the request to NSO
    response = requests.post(
        nso_url,
        json=nso_command,
        auth=HTTPBasicAuth(username, password)
    )

    if response.status_code == 200:
        # NSO successfully received the request
        data = response.json()
        print("NSO Output:")
        print(data["result"]["msg"])
    else:
        print("Failed to communicate with NSO. Status code:", response.status_code)

except requests.exceptions.RequestException as e:
    print("Error:", e)

 

  1. Replace "http://nso-server:8080/jsonrpc", "your_username", and "your_password" with your NSO server details.

  2. Run the Script:

    Save the script and run it. It will send the specified NSO command, and you should see the output in the console.

This script sends a JSON-RPC request to NSO's REST API endpoint with the provided credentials and command. It then extracts and prints the command output from the response.

Make sure to adapt this script to your specific NSO environment, such as authentication and API endpoint, and replace the example command with the one you want to execute.