nxos

package module
v0.6.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 15, 2026 License: MPL-2.0 Imports: 16 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Tests

go-nxos

go-nxos is a Go client library for Cisco NX-OS devices. It is based on Nathan's excellent goaci module and features a simple, extensible API and advanced JSON manipulation.

Getting Started

Installing

To start using go-nxos, install Go and go get:

$ go get -u github.com/netascode/go-nxos

Basic Usage
package main

import "github.com/netascode/go-nxos"

func main() {
    client, _ := nxos.NewClient("1.1.1.1", "user", "pwd", true)

    res, _ := client.Get("/api/mo/sys/intf/phys-[eth1/1]")
    println(res.Get("imdata.0.*.attributes.id").String())
}

This will print:

eth1/1
Result manipulation

nxos.Result uses GJSON to simplify handling JSON results. See the GJSON documentation for more detail.

res, _ := client.GetClass("l1PhysIf")
println(res.Get("0.l1PhysIf.attributes.name").String()) // name of first physical interface

for _, int := range res.Array() {
    println(int.Get("*.attributes|@pretty")) // pretty print physical interface attributes
}

for _, attr := range res.Get("#.l1PhysIf.attributes").Array() {
    println(attr.Get("@pretty")) // pretty print BD attributes
}
Helpers for common patterns
res, _ := client.GetDn("sys/intf/phys-[eth1/1]")
res, _ := client.GetClass("l1PhysIf")
res, _ := client.DeleteDn("sys/userext/user-[testuser]")
Device software version

The NX-OS version is retrieved from sys/showversion on first use and cached for the lifetime of the client:

v, _ := client.Version()
println(v.String()) // e.g. "10.6(4)"
if v.AtLeast(nxos.MustParseVersion("10.6(1)")) {
    // use features introduced in 10.6(1)
}
Query parameters

Pass the nxos.Query object to the Get request to add query parameters:

queryInfra := nxos.Query("query-target-filter", `eq(l1PhysIf.id,"eth1/1")`)
res, _ := client.GetClass("l1PhysIf", queryInfra)

Pass as many parameters as needed:

res, _ := client.GetClass("interfaceEntity",
    nxos.Query("rsp-subtree-include", "l1PhysIf"),
    nxos.Query("query-target-filter", `eq(l1PhysIf.id,"eth1/1")`)
)
POST data creation

nxos.Body is a wrapper for SJSON. SJSON supports a path syntax simplifying JSON creation.

exampleInt := nxos.Body{}.Set("l1PhysIf.attributes.id", "eth1/1").Str
client.Post("/api/mo/sys/intf/phys-[eth1/1]", exampleInt)

These can be chained:

int1 := nxos.Body{}.
    Set("l1PhysIf.attributes.id", "eth1/1").
    Set("l1PhysIf.attributes.mode", "trunk")

...or nested:

attrs := nxos.Body{}.
    Set("id", "eth1/1").
    Set("mode", "trunk").
    Str
int1 := nxos.Body{}.SetRaw("l1PhysIf.attributes", attrs).Str
Token refresh

Token refresh is handled automatically. The client keeps a timer and checks elapsed time on each request, refreshing the token every 8 minutes. This can be handled manually if desired:

res, _ := client.Get("/api/...", nxos.NoRefresh)
client.Refresh()

Documentation

See the documentation for more details.

Documentation

Overview

Package nxos is a a Cisco NXOS NX-API REST client library for Go.

Index

Constants

View Source
const DefaultBackoffDelayFactor float64 = 3
View Source
const DefaultBackoffMaxDelay int = 60
View Source
const DefaultBackoffMinDelay int = 4
View Source
const DefaultMaxRetries int = 3

Variables

This section is empty.

Functions

func BackoffDelayFactor added in v0.2.0

func BackoffDelayFactor(x float64) func(*Client)

BackoffDelayFactor modifies the backoff delay factor from the default of 3.

func BackoffMaxDelay added in v0.2.0

func BackoffMaxDelay(x int) func(*Client)

BackoffMaxDelay modifies the maximum delay between two retries from the default of 60.

func BackoffMinDelay added in v0.2.0

func BackoffMinDelay(x int) func(*Client)

BackoffMinDelay modifies the minimum delay between two retries from the default of 4.

func MaxRetries added in v0.2.0

func MaxRetries(x int) func(*Client)

MaxRetries modifies the maximum number of retries from the default of 3.

func NoLogPayload added in v0.2.0

func NoLogPayload(req *Req)

NoLogPayload prevents logging of payloads. Primarily used by the Login and Refresh methods where this could expose secrets.

func NoRefresh

func NoRefresh(req *Req)

NoRefresh prevents token refresh check. Primarily used by the Login and Refresh methods where this would be redundant.

func Query

func Query(k, v string) func(req *Req)

Query sets an HTTP query parameter.

client.GetClass("bgpInst", nxos.Query("query-target-filter", `eq(bgpInst.asn,"100")`))

Or set multiple parameters:

client.GetClass("bgpInst",
  nxos.Query("rsp-subtree-include", "faults"),
  nxos.Query("query-target-filter", `eq(bgpInst.asn,"100")`))

func RequestTimeout

func RequestTimeout(x time.Duration) func(*Client)

RequestTimeout modifies the HTTP request timeout from the default of 60 seconds.

Types

type AuthenticationError added in v0.5.2

type AuthenticationError struct {
	StatusCode int
	Message    string
}

AuthenticationError indicates that the device was reachable but rejected the supplied credentials (HTTP 401/403).

func (*AuthenticationError) Error added in v0.5.2

func (e *AuthenticationError) Error() string

type Body

type Body struct {
	Str string
}

Body wraps SJSON for building JSON body strings. Usage example:

Body{}.Set("bgpInst.attributes.asn", "100").Str

func (Body) Delete added in v0.2.3

func (body Body) Delete(path string) Body

Delete deletes a JSON path.

func (Body) Res

func (body Body) Res() Res

Res creates a Res object, i.e. a GJSON result object.

func (Body) Set

func (body Body) Set(path, value string) Body

Set sets a JSON path to a value.

func (Body) SetRaw

func (body Body) SetRaw(path, rawValue string) Body

SetRaw sets a JSON path to a raw string value. This is primarily used for building up nested structures, e.g.:

Body{}.SetRaw("bgpInst.attributes", Body{}.Set("asn", "100").Str).Str

type Client

type Client struct {
	// HttpClient is the *http.Client used for API requests.
	HttpClient *http.Client
	// List of URLs.
	Url string
	// LastRefresh is the timestamp of the last token refresh interval.
	LastRefresh time.Time
	// Token is the current authentication token
	Token string
	// Usr is the NXOS device username.
	Usr string
	// Pwd is the NXOS device password.
	Pwd string
	// Insecure determines if insecure https connections are allowed.
	Insecure bool
	// Maximum number of retries
	MaxRetries int
	// Minimum delay between two retries
	BackoffMinDelay int
	// Maximum delay between two retries
	BackoffMaxDelay int
	// Backoff delay factor
	BackoffDelayFactor float64
	// contains filtered or unexported fields
}

Client is an HTTP NXOS NX-API client. Use nxos.NewClient to initiate a client. This will ensure proper cookie handling and processing of modifiers.

func NewClient

func NewClient(url, usr, pwd string, insecure bool, mods ...func(*Client)) (*Client, error)

NewClient creates a new NXOS HTTP client. Pass modifiers in to modify the behavior of the client, e.g.

client, _ := NewClient("apic", "user", "password", true, RequestTimeout(120))

func (*Client) Authenticate

func (client *Client) Authenticate() error

Login if no token available or refresh the token if older than 480 seconds.

func (*Client) Backoff added in v0.2.0

func (client *Client) Backoff(attempts int) bool

Backoff waits following an exponential backoff algorithm

func (*Client) DeleteDn

func (client *Client) DeleteDn(dn string, mods ...func(*Req)) (Res, error)

DeleteDn makes a DELETE request by DN.

func (*Client) Do

func (client *Client) Do(req Req) (Res, error)

Do makes a request. Requests for Do are built ouside of the client, e.g.

req := client.NewReq("GET", "/api/mo/sys/bgp", nil)
res, _ := client.Do(req)

func (*Client) Get

func (client *Client) Get(path string, mods ...func(*Req)) (Res, error)

Get makes a GET request and returns a GJSON result. Results will be the raw data structure as returned by the NXOS device, wrapped in imdata, e.g.

{
  "totalCount": "1",
  "imdata": [
    {
      "bgpEntity": {
        "attributes": {
          "adminSt": "enabled",
          "dn": "sys/bgp",
          "name": "bgp"
        }
      }
    }
  ]
}

func (*Client) GetClass

func (client *Client) GetClass(class string, mods ...func(*Req)) (Res, error)

GetClass makes a GET request by class and unwraps the results. Result is removed from imdata, but still wrapped in Class.attributes, e.g.

[
  {
    "bgpEntity": {
      "attributes": {
        "dn": "sys/bgp",
        "name": "bgp",
      }
    }
  }
]

func (*Client) GetDn

func (client *Client) GetDn(dn string, mods ...func(*Req)) (Res, error)

GetDn makes a GET request by DN. Result is removed from imdata and first result is removed from the list, e.g.

{
  "bgpEntity": {
    "attributes": {
      "dn": "sys/bgp",
      "name": "bgp",
    }
  }
}

func (*Client) JsonRpc added in v0.3.1

func (client *Client) JsonRpc(commands []string, mods ...func(*Req)) (Res, error)

JsonRpc makes a JSON-RPC request with one or more commands and returns a GJSON result.

func (*Client) Login

func (client *Client) Login() error

Login authenticates to the NXOS device.

func (*Client) NewReq

func (client *Client) NewReq(method, uri string, body io.Reader, mods ...func(*Req)) Req

NewReq creates a new Req request for this client.

func (*Client) Post

func (client *Client) Post(dn, data string, mods ...func(*Req)) (Res, error)

Post makes a POST request and returns a GJSON result. Hint: Use the Body struct to easily create POST body data.

func (*Client) Put added in v0.1.1

func (client *Client) Put(dn, data string, mods ...func(*Req)) (Res, error)

Put makes a PUT request and returns a GJSON result. Hint: Use the Body struct to easily create PUT body data.

func (*Client) Refresh

func (client *Client) Refresh() error

Refresh refreshes the authentication token. Note that this will be handled automatically be default. Refresh will be checked every request and the token will be refreshed after 8 minutes. Pass nxos.NoRefresh to prevent automatic refresh handling and handle it directly instead.

func (*Client) Version added in v0.6.0

func (client *Client) Version() (Version, error)

Version returns the NX-OS software version of the device. The version is retrieved from "sys/showversion" on first use and cached for the lifetime of the client. Failed attempts are not cached, so a subsequent call will retry.

type Req

type Req struct {
	// HttpReq is the *http.Request obejct.
	HttpReq *http.Request
	// Refresh indicates whether token refresh should be checked for this request.
	// Pass NoRefresh to disable Refresh check.
	Refresh bool
	// LogPayload indicates whether logging of payloads should be enabled.
	LogPayload bool
	// OverrideUrl indicates a URL to use instead
	OverrideUrl string
}

Req wraps http.Request for API requests.

type Res

type Res = gjson.Result

Res is an API response returned by client requests. This is a GJSON result, which offers advanced and safe parsing capabilities. https://github.com/tidwall/gjson

type Version added in v0.6.0

type Version struct {
	// Major is the major release number, e.g. 10 in "10.6(4)".
	Major int
	// Minor is the minor release number, e.g. 6 in "10.6(4)".
	Minor int
	// Maintenance is the maintenance release number, e.g. 4 in "10.6(4)".
	Maintenance int
	// Rebuild is the optional rebuild suffix, e.g. "a" in "10.3(4a)".
	// It is not considered when comparing versions.
	Rebuild string
	// Raw is the original version string.
	Raw string
}

Version is a parsed NX-OS software version, e.g. "10.6(4)" or "10.3(4a)".

func MustParseVersion added in v0.6.0

func MustParseVersion(s string) Version

MustParseVersion is like ParseVersion but panics if the version cannot be parsed.

func ParseVersion added in v0.6.0

func ParseVersion(s string) (Version, error)

ParseVersion parses an NX-OS version string such as "10.6(4)", "10.3(4a)" or "9.3(10)". Trailing train information (e.g. "I7(9)" in "7.0(3)I7(9)") is ignored.

func (Version) AtLeast added in v0.6.0

func (v Version) AtLeast(other Version) bool

AtLeast returns true if v is equal to or higher than other.

func (Version) Compare added in v0.6.0

func (v Version) Compare(other Version) int

Compare returns -1, 0 or 1 if v is lower than, equal to or higher than other. Only major, minor and maintenance numbers are compared.

func (Version) String added in v0.6.0

func (v Version) String() string

String returns the original version string, or a normalized one if not available.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL