Legrand / Raritan Xerus™ JSON-RPC API for Remote Access Devices like KX4-101, KX3G2
Loading...
Searching...
No Matches
Python JSON-RPC Client Binding

Prerequisites

Linux

Standard Python 2 or Python 3 installations already contain all necessary packages.

Windows

  • download and install the latest Python 2 or Python 3 from https://www.python.org/downloads/
  • the installation will associated the file extension *.py with python, so you can start python files directly from the command line or the file manager

Authentication

In examples below, replace my_user and my_pass with Default Credentials of your product, or your own credentials.

SSL Certificate Verification

All Xerus devices enforce use of HTTPS when accessing the JSON-RPC service. By default, programs written with this client binding try to verify the authenticity of the server when connecting. This requires a valid SSL certificate to be installed on the device. When trying to connect to a device without a valid SSL certificate the client program will terminate with an error message.

It is possible to disable the SSL certificate verification by adding a disable_certificate_verification option to the arguments of the rpc.Agent instance:

Code:

agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass", disable_certificate_verification = True)

Timeout for IDL methods

Per default, there is no time limit for the IDL method calls configured and so the function calls might not return if the target device is not available.

If necessary, a timeout in seconds can be provided by adding a timeout option to the arguments of the rpc.Agent instance.

Code:

agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass", timeout = 5)

Examples

Getting device information:

Code:

from xeruskvm import rpc
from xeruskvm.rpc import radm
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
kvm_mgr = radm.KvmManager("/radm/kvmmanager", agent)
kvm_dev = kvm_mgr.getKvmDevice()
metadata = kvm_dev.getMetadata()
print(metadata)

Output produced if there is no error:

* serialNumber = "33I4079262"
* product = "KX3G2"
* model = "DKX3G2-464"
* fwVersion = "4.1.0.5.52267"
* hwVersion = "0x18"
* macAddress = "02:d9:75:38:eb:10"
* privilegeArg = ""
* uid = "D_02d97538eb10"
* idx = 0

Configuring the SNMP agent:

Code:

from xeruskvm import rpc
from xeruskvm.rpc import devsettings
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
snmp_proxy = devsettings.Snmp("/snmp", agent)
config = snmp_proxy.getConfiguration()
config.v2enable = True
config.readComm = "public"
config.writeComm = "private"
snmp_proxy.setConfiguration(config)
SNMP agent settings interface.
Definition Snmp.idl:14

Note that the URIs given to the object proxies (such as "/auth/user") are well-known references to static (i.e. they are always there) object instances implemented by the device. All well-known references along with their interface are documented in Well-Known Resource IDs.

More Examples

Additional Python examples for selected interfaces can be found on the following details pages:

IDL-to-Python Mapping

Modules and Python Packages

All supporting and generated symbols are placed underneath common package xeruskvm.rpc. IDL modules are mapped to corresponding Python packages within this common package. Import of all definitions within a module can be done via (for instance):

from xeruskvm.rpc.usermgmt import *

Interfaces and Methods

IDL interfaces are mapped to Python classes which are defined in the __init__.py file of their according package. The python class implements a proxy that delegates calls to its IDL defined methods to the actual object implementation across the network.

The signature of the methods is slightly altered compared to the IDL signature. All in arguments are expected as arguments to the Python method in the same order as they appear in IDL. The return argument, if any, and all out arguments are returned as a Python tuple in the same order they appear in IDL. That means if there is a return argument defined it will appear as first element in the tuple, otherwise the first out argument is the first element in the tuple. If the IDL method has either only a return value or a single out argument, a single value is returned by the Python method without an embracing tuple.

Structures

IDL structures are mapped to Python classes which are, like all other definitions, defined in the __init__.py file of their according package. The class has all elements as defined in IDL. In addition there is a constructor with a signature that initializes all elements.

The following is an example for enabling a threshold in a sensor:

from xeruskvm import rpc
from xeruskvm.rpc import usermgmt
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
user_mgr = usermgmt.UserManager("/auth/user", agent)
username = "testuser3"
accounts = user_mgr.getAllAccounts()
acc_found = next(filter(lambda acc: acc.name == username, accounts), None)
if acc_found:
print(f"Found user: {acc_found.name}")
print("User Info:")
print(acc_found.info)
else:
print(f"User '{username}' not found.")
User manager interface

Enumerations

An IDL enumeration is mapped to a concrete class which has an element for each enumerated value. That means access to a particular enumerated value is accomplished by naming the enumeration type and the enumerated value. Consider the following example for checking a user's SNMPv3 security level:

# usermgmt has been imported and acc_found has been initialized before, see above
if acc_found.info.snmpV3Settings.secLevel == usermgmt.SnmpV3SecLevel.NO_AUTH_NO_PRIV:
print("No authentication and no privacy protocol")

SnmpV3SecLevel is an enumerated type defined in the usermgmt package. NO_AUTH_NO_PRIV is a specific enumerated value defined in the SnmpV3SecLevel enumeration.

Vectors

IDL vectors are mapped to Python lists. Consider the following example for looping over the list of all account names and printing them:

from xeruskvm import rpc
from xeruskvm.rpc import usermgmt
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
user_mgr = usermgmt.UserManager("/auth/user", agent)
# List all registered users
usernames = user_mgr.getAccountNames()
if usernames:
print("Registered Users:")
for name in usernames:
print(f"- {name}")
else:
print("No user found.")

Maps

IDL maps are mapped to Python dictionaries. Consider the following example for looping over all KVM port groups, retrieved as a map with group IDs as keys and radm.PortGroup values, printing each group ID and name:

from xeruskvm import rpc
from xeruskvm.rpc import radm
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
kvm_mgr = radm.KvmManager("/radm/kvmmanager", agent)
port_groups = kvm_mgr.getPortGroupManager().getAllPortGroups()
for group_id, group in port_groups.items():
print(group_id, group.getSettings().name)

Exceptions

Execptional errors conditions may occur because of communication problems or encoding/decoding problems, or because of system errors that occur on the server while processing a request. Reporting of such error conditions is not part a regular IDL signature but part of the JSON-RPC protocol.

The Python implementation of the JSON-RPC protocol maps these error condtions to exception:

  • xeruskvm.rpc.HttpException

    This exception is raised in case a communication error occurred. Typical examples include an unreachable server or a failed authentication. The exception contains a descriptive text that gives more details on the error condition.

  • xeruskvm.rpc.JsonRpcErrorException

    This exception is raised in case an error happened on the server side while processing the request. The device might be in an unexpected state. Also there might be a version mismatch between client and server, which means the communication contract between client and server as specified by IDL is broken. The exception contains a descriptive text that gives more details on the error condition.

  • xeruskvm.rpc.JsonRpcSyntaxException

    This exception is raised in case demarshaling of a JSON message went wrong. This may indicate a version mismatch between client and server. The exception contains a descriptive text that gives more details on the error condition.

Consider the following example for catching a communication error:

from xeruskvm import rpc
from xeruskvm.rpc import security
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
sec = security.Security("/security", agent)
try:
ssh_settings = sec.getSSHSettings()
except rpc.HttpException as e:
print(f"Failed to get SSH Settings:\n {e}")
else:
print(ssh_settings)
Security configuration interface
Definition Security.idl:156

Bulk Requests

The Bulk RPC interface allows combining multiple JSON-RPC method calls into a single bulk request that can be sent to the server and processed in a single HTTP request. The xeruskvm.rpc.BulkRequestHelper class provides a convenient interface to collect and execute method calls:

  1. Create a BulkRequestHelper instance.
  2. Queue one or more method calls with the add_request() method.
  3. Call perform_bulk() to submit the bulk request.
  4. Use clear() to empty the request and response lists before using the BulkRequestHelper instance again.

perform_bulk() returns a list containing one entry per queued request. Each entry can be one of the following:

  • None if the called method returns void and has no out parameters.
  • A single value if the method has exactly one return type or out parameter.
  • A tuple if the method has more than one return type/out parameter.
  • An Exception object if the request has failed and the optional raise_subreq_failure argument is False.

Example 1:

from xeruskvm import rpc
from xeruskvm.rpc import devsettings
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
snmp_proxy = devsettings.Snmp("/snmp", agent)
cfg = snmp_proxy.getConfiguration()
cfg.v2enable = True
bulk_helper = rpc.BulkRequestHelper(agent)
bulk_helper.add_request(snmp_proxy.getV3EngineId)
bulk_helper.add_request(snmp_proxy.setConfiguration, cfg)
responses = bulk_helper.perform_bulk(raise_subreq_failure = False)
if isinstance(responses[0], Exception):
print("Snmp.getV3EngineId() failed: %s" % (responses[0]))
else:
print("SNMP engine ID: %s" % (responses[0]))
if isinstance(responses[1], Exception):
print("Snmp.setConfiguration() failed: %s" % (responses[1]))
else:
print("Result of setConfiguration(): %d" % (responses[1]))

Example 2: using perform_bulk() wrapper for steps 1–3 above

from xeruskvm.rpc import perform_bulk
channels = kvm_mgr.getKvmChannels()
metadatas = perform_bulk(agent, [(chan.getMetadata, []) for chan in channels])

Agent Method Reference

xeruskvm.rpc.Agent(proto, host, user=None, passwd=None, token=None, debug=False, disable_certificate_verification=False, timeout=None)

Creates a new agent.

Parameters:

  • proto: Used protocol (either "https" or "http")
  • host: Hostname or IP address of the target KVM device
  • user: User name (optional)
  • passwd: Password (optional)
  • token: Authentication token (optional)
  • debug: Enables debug output (optional, True/False)
  • disable_certificate_verification: Disables HTTPS certificate verification (optional, True/False)
  • timeout: Request timeout (optional, in seconds)

If neither username/password nor token are specified, it is necessary to call either set_auth_basic() or set_auth_token() before the first request.

agent.set_auth_basic(user, password)

This method enables HTTP basic authentication using username and password.

Parameters:

  • user: User name
  • password: password
agent.set_auth_token(token)

This method enables HTTP authentication using a session token. A session token can be obtained by calling the newSession method of the session.SessionManager interface.

Parameters:

  • token: Session token

Helper Functions

agent.get(target)

This method performs a HTTP-GET request on the given target.

Parameters:

  • target: target URL
agent.form_data_file(target, datas)

This method HTTP-POST files as multipart form data to the given target. The CGI scripts only accept files with valid formnames. Valid formnames are:

  • "key_file" and "cert_file" for key or certificate files (used in xeruskvm.rpc.cert.upload)
  • "bulk_config_file" for bulk configuration files (used in xeruskvm.rpc.bulkcfg.upload)
  • "upfile" for firmware update files (used in xeruskvm.rpc.firmware.upload)
  • "config_file" for raw configuration files (used in xeruskvm.rpc.rawcfg.upload)

Parameters:

  • target: target URL
  • datas: list of file data dicts, which must contain:
    • data: binary file data
    • filename: file name
    • formname: formname
    • mimetype: mimetype (usually "application/octet-stream")

Firmware Update

Upgrading the device firmware requires uploading the binary firmware image in advance. The Python SDK offers a convenience method firmware.upload() for this task.

Checking the image status and initiating the actual update process are done using the firmware.Firmware interface.

Example:

from xeruskvm import rpc
from xeruskvm.rpc import firmware
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
firmware_proxy = firmware.Firmware("/firmware", agent)
# read file in binary mode
fwFile = open("kx3-kx3-040100-52266-sec-prod.rfp", "rb")
# upload
firmware.upload(agent, fwFile.read())
image_present, image_info = firmware_proxy.getImageInfo()
# check for successful upload
if not image_present:
print("Upload failed")
else:
print(image_info)
# start update
firmware_proxy.startUpdate([])
Firmware management methods
Definition Firmware.idl:123

Note

If the device is configured to force https and a firmware update file is uploaded with an agent which is configured to use http, then the upload may fail with a broken pipe exception. This issue can be worked around by setting the agent protocol to https.

Certificate Upload and installation

It is possible to upload and install own certificates. The Certificate upload needs at least one file:

  1. certificate file (e.g. my-cert.crt)
  2. key file (optional, e.g. my-key.key)

After uploading the function returns a response code. Known response codes are:

Response Code Description
0 Operation was successful
1 An internal error occurred
2 A pending certificate or certificate signing request is already present.
3 The key is invalid.
4 The certificate is invalid.
5 The key and certificate do not match.
any other An internal error occurred

It is recommended that the user verifies the pending certificate before installation.

Function signature

xeruskvm.rpc.cert.upload(agent, certData, keyData=None)

Example:

from xeruskvm import rpc
from xeruskvm.rpc import cert
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
ssl_proxy = cert.ServerSSLCert("/server_ssl_cert", agent)
# read files in binary mode
certFile = open("my-cert.crt", "rb")
keyFile = open("my-key.key", "rb")
# upload
code = cert.upload(agent, certFile.read(), keyFile.read())
# view return code
print(code)
# view pending
print(ssl_proxy.getInfo().pendingCertInfo)
# install
ssl_proxy.installPendingKeyPair()
# view active
print(ssl_proxy.getInfo().activeCertInfo)
TLS certificate management interface.

Certificate Download

It is possible to download the installed certificates and keys.

Function signature:

xeruskvm.rpc.cert.download(agent, tag="active_cert")

Allowed values for the tag parameter are:

"active_cert", "active_key", "new_cert", "new_key", "new_req"

Example:

from xeruskvm import rpc
from xeruskvm.rpc import cert
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# download the current installed certificate
certificate = cert.download(agent, "active_cert")
# view the certificate
print(certificate)

Raw Configuration Upload

It is possible to upload a raw configuration. The raw configuration upload needs one file:

  1. raw configuration file (e.g. config.txt)

After uploading a raw configuration a response code is returned. Known response codes are:

Response Code Description
0 Operation was successful
1 An internal error occurred
2 A parameter error occurred
3 A raw config update operation is already running
4 The file is too large
5 Invalid raw config file provided
6 Invalid device list file or match provided
7 Device list file required but missing (must be the first uploaded file)
8 No matching entry in device list found
9 Macro subsitution error
10 Decrypting value failed
11 Unknown magic line
12 Processing magic line fail

Example:

from xeruskvm import rpc
from xeruskvm.rpc import rawcfg
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# read file in binary mode
cfg_file = open("config.txt", "rb")
# upload
code = rawcfg.upload(agent, cfg_file.read())
# output response code
print(code)

Raw Configuration Download

It is possible to download the raw configuration.

Example:

from xeruskvm import rpc
from xeruskvm.rpc import rawcfg
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# download
rawconfig = rawcfg.download(agent)
# output raw configuration
print(rawconfig)

Bulk Configuration Upload

It is possible to upload a bulk configuration. The bulk configuration upload needs one file:

  1. bulk configuration file (e.g. bulk_config.txt)

After uploading a bulk configuration a response code is returned. Known response codes are:

Response Code Description Comment
0 Operation was successful
1 An internal error occurred
2 A parameter error occurred
3 Invalid XML data provided legacy / unused
4 The config data is incompatible (device type mismatch)
5 The config data is incompatible (device model mismatch)
6 The config data is incompatible (firmware version mismatch)
7 The config data is incompatible (unknown data type) legacy / unused
8 The config data is invalid legacy / unused
9 Checksum of config data is wrong legacy / unused
10 Mode mismatch (bulk config vs. full config) legacy / unused
11 Restore operation already running
12 File too large
13 File invalid
14 Checksum missing or invalid
15 Unknown filters

Example:

from xeruskvm import rpc
from xeruskvm.rpc import bulkcfg
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# read file in binary mode
cfg_file = open("bulk_config.txt", "rb")
# upload
code = bulkcfg.upload(agent, cfg_file.read())
# view code
print(code)

The bulk configuration upload support different modes, these modes are:

  • restore a backup (backup=True)
  • restore a bulk configuration (default)

For switching the modes, use the parameter backup from the upload function.

Example:

# backup mode
code = bulkcfg.upload(agent, cfg_file.read(), backup=True)

Further optional parameters are:

  • password (default is emtpy string) for encrypted configuration files
  • skip_check (default is empty string, allowed values are "model", "firmware_version" or "firmware_version,model") for ignoring the model and/or firmware version

Function signature:

xeruskvm.rpc.bulkcfg.upload(agent, data, backup=False, password="", skip_check="")

Bulk Configuration Download

It is possible to download the bulk configuration.

Example:

from xeruskvm import rpc
from xeruskvm.rpc import bulkcfg
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# download
bulkconfig = bulkcfg.download(agent)
# output bulk configuration
print(bulkconfig)

The bulk configuration download support different modes, these modes are:

  • restore a backup (backup=True)
  • restore a bulk configuration (default)

For switching the modes, use the parameter backup from the upload function.

Example:

# backup mode
code = bulkcfg.download(agent, backup=True)

Further optional parameters are:

  • password (default is emtpy string, ignored if clear_text set to True) for encrypting configuration files
  • clear_text (default is False) download configuration as clear text
  • filter_profile (default is empty string) define a configuration filter profile by name

Function signature:

xeruskvm.rpc.bulkcfg.download(agent, backup=False, password="", clear_text=False, filter_profile="")

Diagnostic Data Download

It is possible to download the diagnostic data.

Example:

from xeruskvm import rpc
from xeruskvm.rpc import diag
agent = rpc.Agent("https", "my-xeruskvm.example.com", "my_user", "my_pass")
# download
diag = diag.download(agent)
# view diagnostic data
print(diag)

Zeroconf Device Discovery

By default all Xerus products advertise their services using the MDNS Zeroconf protocol. The helper function zeroconf.discover() can be used to search for devices in the local subnet. It returns a list of discovered devices as dictionaries with IP address, port, firmware version and serial number.

Using this feature requires the zeroconf Python library that can be installed with pip install zeroconf. This package is only available for Python version 3.6 and later.

Example:

from xeruskvm import zeroconf
devices = zeroconf.discover()
print(devices)
# [{'ip': '192.168.5.209', 'port': 443, 'fw': '4.3.13.5-52458', 'serial': '33M5400034'}]