pyGNMI

repository·master·Indexed 41 days ago

https://github.com/akarneliuk/pygnmi

A pure Python implementation of a gNMI client used to interact with network functions via gRPC. It supports standard gNMI RPCs including Capabilities, Get, Set, and Subscribe, and is tested against NOS such as Arista EOS, Nokia SR OS, Cisco IOS XR, Juniper JUNOS, Nokia SRLinux, and Cisco NX-OS. The library provides the gNMIclient class for session management, a telemetryParser for converting Protobuf messages to Python dictionaries, and a pygnmicli command-line tool.

Tokens
4.1K
Snippets
16
Records
23
Agent score
50%

What's inside pyGNMI

  1. Understand gNMI Path naming conventions

    master

    The library supports several path naming conventions, automatically converting them to the canonical format /origin:element1/element2.... Supported formats include:

    • yang-module:container/container[key=value]
    • /yang-module:container/container[key=value]
    • /yang-module:/container/container[key=value]
    • /container/container[key=value]

    You can also omit the YANG module name if the vendor implementation requires it: /element1/element2....

  2. Use subscribe2() for telemetry collection

    master

    For building telemetry collectors, it is highly recommended to use the subscribe2() method instead of the older subscribe() method. subscribe2() is actively developed, thoroughly tested, and supports all telemetry modes (STREAM, ONCE, POLL) by simply providing a corresponding dictionary as input. It also includes automatic use of telemetryParser and proper qos support.

    # Example concept: subscribe2() is the preferred method for telemetry
    # client.subscribe2(input_dict)
  3. Quickstart with pyGNMI client

    master

    To interact with network functions using gNMI, use the gNMIclient class from pygnmi.client. The client is designed to be used as a context manager. You can perform operations like get by providing a list of paths.

    Supported RPCs include:

    • Capabilities
    • Get
    • Set
    • Subscribe

    Supported operation modes:

    • Insecure gRPC channel (without encryption)
    • Secure gRPC channel (with encryption and authentication based on certificate)
    # Modules
    from pygnmi.client import gNMIclient
    
    # Variables
    host = ('169.254.255.64', '57400')
    
    # Body
    if __name__ == '__main__':
        with gNMIclient(target=host, username='admin', password='admin', insecure=True) as gc:
             result = gc.get(path=['openconfig-interfaces:interfaces', 'openconfig-acl:acl'])
    
        print(result)
  4. Manage gNMI sessions and timeouts

    master

    When working with gNMIclient, consider the following for session management:

    • Context Manager: Use with GNMICLient(...) as client: to ensure the session is properly closed.
    • Manual Close: If not using a context manager, call client.close() explicitly.
    • Timeouts: You can modify the session timeout using the gnmi_timeout key in the gNMIclient constructor.
    • Keepalive: The library supports a keepalive timer for gRPC sessions to prevent automatic closure (e.g., after 2 hours).
  5. Configure gNMIclient authentication and security

    master

    The gNMIclient supports several authentication and security configurations:

    • Token Authentication: For platforms like Arista CVP, provide a token using the token argument: gNMIclient(token=TOKEN).
    • Username/Password: Standard authentication via username and password arguments.
    • TLS/SSL Verification: Use the skip_verify argument to bypass certificate verification. For this to work, the certificate must contain at least one subject alternative name (DNS, IP, etc.).
    • Insecure Channels: Supported for platforms like Nokia SR OS.
    • Custom SSL Ciphers: You can dynamically change GRPC_SSL_CIPHER_SUITES to HIGH for specific requirements (e.g., Nokia SR OS).
    # Token-based authentication
    client = GNMICLient(target='1.1.1.1', token='YOUR_TOKEN')
    
    # Skip TLS verification
    client = GNMICLient(target='1.1.1.1', skip_verify=True)
  6. Understand the telemetry data format

    master

    The telemetryParser converts gNMI Protobuf messages into a Python dictionary. The resulting structure typically follows this pattern:

    • update: A dictionary containing:
      • prefix: The resource path string (e.g., /interfaces/interface[name=eth0]).
      • timestamp: The timestamp of the update.
      • update: A list of individual path/value updates.
        • path: The specific path to the value.
        • val: The actual value (parsed into Python types like int, str, dict for JSON, etc.).
      • delete: (Optional) A list of paths that were deleted.
    • sync_response: (Optional) Metadata indicating the end of a synchronization period.
  7. Configure encoding in pygnmi

    master

    The encoding parameter can be specified in get(), set(), and subscribe2() methods.

    If encoding is not explicitly provided by the user, pygnmi automatically detects supported encodings by calling capabilities() during the connect() phase. It prioritizes json first, followed by json_ietf.

  8. Use the pygnmicli command-line tool

    master

    The pygnmicli tool allows interacting with gNMI devices via the CLI. Key features include:

    • Encoding: Use -e or --encoding to specify the encoding (overrides default).
    • Authentication: Supports --token for token-based authentication.
    • History Extensions: Supports the --history flag.
    • QoS: Supports the --no-qos-marking flag.
    • Prefix: Supports adding a prefix to commands.
  9. Initialize the gNMIclient

    master

    The gNMIclient class is the primary interface for interacting with network devices via gNMI. You can initialize it with connection details such as target, credentials, and security settings.

    Key Parameters:

    • target: A tuple (host, port) or a string for Unix domain sockets.
    • username / password: Credentials for authentication.
    • insecure: Set to True to use an insecure gRPC channel.
    • path_cert, path_key, path_root: Paths to SSL/TLS certificates for secure connections.
    • skip_verify: If True, the client attempts to automatically resolve certificate mismatches by extracting Common Names (CN) or Subject Alternative Names (SANs) from the device certificate.
    • gnmi_timeout: Connection timeout in seconds.
    • token: An optional access token for bearer authentication.
    from pygnmi.client import gNMIclient
    
    client = gNMIclient(
        target=('192.168.1.1', 50051),
        username='admin',
        password='password',
        path_cert='client.crt',
        path_key='client.key',
        path_root='ca.crt'
    )
  10. Perform a set operation with retry logic

    master

    If you encounter transient failures (specifically StatusCode.FAILED_PRECONDITION, often due to lock contention or system startup), use set_with_retry(). This method attempts the set() operation once, and if it fails with the specified error, it waits for a retry_delay (default 3s) and tries one more time.

    # Retries once after a FAILED_PRECONDITION error
    client.set_with_retry(update=my_updates, retry_delay=5)