netconf¶
This package supports creating both netconf clients and servers. Additionally a CLI netconf utility is included.
Additionally netconf uses _sshutil and thus supports your SSH agent and SSH config when using the client as well as socket caching for optimal performance.
Contents:
Installation¶
At the command line:
$ pip install netconf
Or, if you have virtualenvwrapper installed:
$ mkvirtualenv netconf
$ pip install netconf
CLI Client¶
Hello - Get Capabilities¶
To get the capabilities of a server:
$ netconf-client … --hello
urn:ietf:params:netconf:base:1.1
urn:ietf:params:netconf:base:1.0
urn:ietf:params:xml:ns:yang:ietf-system
urn:ietf:params:netconf:capability:xpath:1.0
Authentication¶
You can authenticate to the server using passwords, ssh keys, or your ssh agent. Below are some examples of all of these uses.
Password Authentication¶
$ # Using a password
$ netconf-client … --username=admin --password=admin
$ # Using a password in an environment variable
$ export PASS=admin
$ netconf-client … --username=admin --password=env:PASS
$ # Using a password in a file.
$ echo "admin" > passfile
$ netconf-client … --username=admin --password=file:passfile
SSH Authentication¶
$ # Using a key from your SSH agent
$ netconf-client …
$ # Using a keyfile
$ netconf-client … --keyfile=~/.ssh/id_rsa
$ # Using a key from an environment variable (useful in CI environments)
$ export MYKEY="$(cat ~/.ssh/id_rsa)"
$ netconf-client … --keyfile=<(echo "$MYKEY") --hello
$ # Using a keyfile with a passphrase from an environment variable
$ export PASS="mypassphrase"
$ netconf-client … --keyfile=~/.ssh/id_rsa --password=env:PASS
$ # Using a keyfile with a passphrase from a file
$ echo "mypassphrase" > passfile
$ netconf-client … --keyfile=~/.ssh/id_rsa --password=file:passfile
Get Config¶
To request config (see Authentication for authentication).
$ netconf-client … --get-config
<data xmlns="urn:ietf:params:xml:ns:netconf:base:1.0">
<sys:system xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:hostname>tops</sys:hostname>
<sys:clock>
<sys:timezone-utc-offset>180</sys:timezone-utc-offset>
</sys:clock>
</sys:system>
</data>
To request config filtered by an xpath expression.
$ netconf-client … --get-config="/sys:system/sys:clock"
--namespaces="sys=urn:ietf:params:xml:ns:yang:ietf-system"
<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<sys:system xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:clock>
<sys:timezone-utc-offset>180</sys:timezone-utc-offset>
</sys:clock>
</sys:system>
</nc:data>
Get State¶
To request operational state (see Authentication for authentication)
$ netconf-client … --get
<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<sys:system xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:hostname>tops</sys:hostname>
<sys:clock>
<sys:timezone-utc-offset>180</sys:timezone-utc-offset>
</sys:clock>
</sys:system>
<sys:system-state xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:platform>
<sys:os-name>Linux</sys:os-name>
<sys:os-release>5.4.14-arch1-1</sys:os-release>
<sys:os-version>#1 SMP PREEMPT Thu, 23 Jan 2020 10:07:05 +0000</sys:os-version>
<sys:machine>x86_64</sys:machine>
</sys:platform>
<sys:clock>
<sys:current-datetime>2020-02-11T18:20:14.516992</sys:current-datetime>
<sys:boot-datetime>2020-02-10T06:31:26.787100</sys:boot-datetime>
</sys:clock>
</sys:system-state>
</nc:data>
To request state filtered by a sub-tree XML filter
$ netconf-client --port=8300 -u admin -p admin --get '<system-state><platform/></system-state>'
<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<sys:system-state xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:platform>
<sys:os-name>Linux</sys:os-name>
<sys:os-release>5.4.14-arch1-1</sys:os-release>
<sys:os-version>#1 SMP PREEMPT Thu, 23 Jan 2020 10:07:05 +0000</sys:os-version>
<sys:machine>x86_64</sys:machine>
</sys:platform>
</sys:system-state>
</nc:data>
To request state filtered by an xpath expression.
$ netconf-client … --get="/sys:system-state/sys:clock" \
--namespaces="sys=urn:ietf:params:xml:ns:yang:ietf-system"
<nc:data xmlns:nc="urn:ietf:params:xml:ns:netconf:base:1.0">
<sys:system-state xmlns:sys="urn:ietf:params:xml:ns:yang:ietf-system">
<sys:clock>
<sys:current-datetime>2020-02-11T18:27:16.336916</sys:current-datetime>
<sys:boot-datetime>2020-02-10T06:31:26.787025</sys:boot-datetime>
</sys:clock>
</sys:system-state>
</nc:data>
Development Usage¶
Netconf Client¶
Sessions¶
To open a session to server:
from netconf.client import NetconfSSHSession
session = NetconfSSHSession(host, port, username, password)
config = session.get_config()
# ...
To open a session with a context manager:
from netconf.client import connect_ssh
with connect_ssh(host, port, username, password) as session:
config = session.get_config()
# ...
To close a session:
session.close()
State¶
To get the operational state from a server:
config = session.get()
To get a specific selection of state using xpath from a server:
config = session.get(select="/devices/device[name='RouterA']")
To get a specific selection of state using XML subtree filter from a server:
config = session.get(select="<devices><device><name>RouterA</name></device></devices>")
Config¶
To get the running config from a server:
config = session.get_config()
To get candidate config from a server:
config = session.get_config(source="candidate")
To get a specific selection of config using xpath from a server:
config = session.get_config(select="/devices/device[name='RouterA']")
To get a specific selection of config using XML subtree filter from a server:
config = session.get_config(select="<devices><device><name>RouterA</name></device></devices>")
To send and RPC to a server:
rpcout = session.send_rpc("<my-rpc/>")
Netconf Server¶
To create a simple server listening on port 830 that handles one RPC <my-cool-rpc>
:
from netconf import nsmap_update, server
import netconf.util as ncutil
MODEL_NS = "urn:my-urn:my-model"
nsmap_update({'pfx': MODEL_NS})
class MyServer (object):
def __init__ (self, user, pw):
controller = server.SSHUserPassController(username=user, password=pw)
self.server = server.NetconfSSHServer(server_ctl=controller, server_methods=self)
def nc_append_capabilities(self, caps):
ncutil.subelm(caps, "capability").text = MODEL_NS
def rpc_my_cool_rpc (self, session, rpc, *params):
data = ncutil.elm("data")
data.append(ncutil.leaf_elm("pfx:result", "RPC result string"))
return data
# ...
server = MyServer("myuser", "mysecert")
# ...
Reference¶
The netconf.client
Module¶
-
class
netconf.client.
NetconfClientSession
(stream, debug=False)¶ Bases:
netconf.base.NetconfSession
Netconf Protocol
-
close
()¶ Close the session.
-
edit_config
(target='running', method='', newconf='', testopt='', erroropt='', timeout=None)¶ Operate on config in ~target~ using ~newconf~ according to ~method~ (“merge”, “replace” or “none”). If “none” then no nodes are modified until a element specifies the mode as an attribute.
Parameters: - target – the target of the config, defaults to “running”.
- method – “merge” (netconf default), “replace” or “none”.
- newconf – The new configuration.
- testopt – “test-then-set” (netconf default), “set” or “test-only”.
- erroropt – “stop-on-error” (netconf default), “continue-on-error” or “rollback-on-error”.
- timeout – A value in fractional seconds to wait for the operation to complete or None for no timeout.
Returns: The result of the edit operation
Return type: lxml.Element
Raises: ReplyTimeoutError, RPCError, SessionError
-
edit_config_async
(target, method, newconf, testopt, erroropt)¶ Operate on config in ~target~ using ~newconf~ according to ~method~ (“merge”, “replace”, “none”). If “none” then no nodes are modified until a element specifies the mode as an attribute.
Parameters: - target – the target of the config.
- method – “merge”, “replace”, “none”.
- newconf – The new configuration.
- testopt – “test-then-set” (netconf default), “set” or “test-only”.
- erroropt – “stop-on-error” (netconf default), “continue-on-error” or “rollback-on-error”.
Returns: The RPC message id which can be passed to wait_reply for the results.
Raises: SessionError
-
get
(select=None, timeout=None)¶ Get operational state from the server. If select is specified it is either an XPATH expression or XML subtree filter for selecting a subsection of the state. If timeout is not None it specifies how long to wait for the get operation to complete.
Parameters: - select – A XML subtree filter or XPATH expression to select a subsection of state.
- timeout – A value in fractional seconds to wait for the operation to complete or None for no timeout.
Returns: The Parsed XML state (i.e., “<data>…</data>”.)
Return type: lxml.Element
Raises: ReplyTimeoutError, RPCError, SessionError
-
get_async
(select)¶ Get operational state asynchronously from the server. If select is specified it is either an XPATH expression or XML subtree filter for selecting a subsection of the state. If timeout is not None it specifies how long to wait for the get operation to complete.
Parameters: select – A XML subtree filter or XPATH expression to select a subsection of state. Returns: The RPC message id which can be passed to wait_reply for the results. Raises: SessionError
-
get_config
(source='running', select=None, timeout=None)¶ Get config for a given source from the server. If select is specified it is either an XPATH expression or XML subtree filter for selecting a subsection of the config. If timeout is not None it specifies how long to wait for the get operation to complete.
Parameters: - source – the source of the config, defaults to “running”.
- select – An XML subtree filter or XPATH expression to select a subsection of config.
- timeout – A value in fractional seconds to wait for the operation to complete or None for no timeout.
Returns: The Parsed XML config (i.e., “<nc:config>…</config>”.)
Return type: lxml.Element
Raises: ReplyTimeoutError, RPCError, SessionError
-
get_config_async
(source, select)¶ Get config asynchronously for a given source from the server. If select is specified it is either an XPATH expression or XML subtree filter for selecting a subsection of the config.
Parameters: - source – the source of the config, defaults to “running”.
- select – An XML subtree filter or XPATH expression to select a subsection of config.
Returns: The RPC message id which can be passed to wait_reply for the results.
Raises: SessionError
-
is_reply_ready
(msg_id)¶ Check whether reply is ready (or session closed)
-
lock
(target='running', timeout=None)¶ Lock target datastore asynchronously.
If timeout is not None it specifies how long to wait for the get operation to complete.
Parameters: target – A string specifying the config datastore to lock. Returns: None Raises: RPCError, SessionError
-
lock_async
(target)¶ Lock target datastore asynchronously.
Parameters: target – A string specifying the config datastore to lock. Returns: The RPC message id which can be passed to wait_reply for the results. Raises: SessionError
-
send_rpc
(rpc, timeout=None)¶ Send a generic RPC to the server and await the reply.
Parameters: (string) (rpc) – The XML of the netconf RPC, not including the <rpc> tag. Returns: (Message as an lxml tree, Parsed reply content, Parsed message content). Return type: (lxml.etree, lxml.Element, lxml.Element) Raises: RPCError, SessionError
-
send_rpc_async
(rpc, noreply=False)¶ Send a generic RPC to the server and await the reply.
Parameters: - rpc (str or lxml.Element) – The XML of the netconf RPC, not including the <nc:rpc> tag.
- noreply (Boolean) – True if no reply is required.
Returns: The RPC message id which can be passed to wait_reply for the results.
-
unlock
(target='running', timeout=None)¶ Unlock target datastore asynchronously.
If timeout is not None it specifies how long to wait for the get operation to complete.
Parameters: target – A string specifying the config datastore to unlock. Returns: None Raises: RPCError, SessionError
-
unlock_async
(target)¶ Unlock target datastore asynchronously.
Parameters: target – A string specifying the config datastore to unlock. Returns: The RPC message id which can be passed to wait_reply for the results. Raises: SessionError
-
wait_reply
(msg_id, timeout=None)¶ Wait for a reply to a given RPC message ID.
Parameters: msg_id – the RPC message ID returned from one of the async method calls Returns: (Message as an lxml tree, Parsed reply content, Parsed message content). Return type: (lxml.etree, lxml.Element, lxml.Element) Raises: RPCError, SessionError
-
-
class
netconf.client.
NetconfSSHSession
(host, port=830, username=None, password=None, debug=False, cache=None, proxycmd=None)¶
-
netconf.client.
connect_ssh
(host, port=830, username=None, password=None, debug=False, cache=None, proxycmd=None)¶ A context manager method for opening a netconf SSH session.
If username is not specified then it will be obtained with getpass.getuser(). If an ssh agent is available it will be used for authentication. A users .ssh/config will be processed for making the ssh connection and any proxycmd found therein will also be utilized.
Parameters: - host – The host to connect to.
- port – The port to connect to.
- username – The username to connect with. If not specified getpass.getuser() will be used
- password – The password or passkey to authenticate with.
- debug – Enable debug logging
- cache – An SSH cache (sshutil.cache) to use for caching connections.
- proxycmd – A proxy command string for connecting with
The netconf.error
Module¶
-
exception
netconf.error.
AccessDeniedAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._AccessDeniedError
-
exception
netconf.error.
AccessDeniedProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._AccessDeniedError
-
exception
netconf.error.
BadAttributeAppError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._BadAttributeError
-
exception
netconf.error.
BadAttributeProtoError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._BadAttributeError
-
exception
netconf.error.
BadAttributeRPCError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._BadAttributeError
-
exception
netconf.error.
BadElementAppError
(origmsg, element, **kwargs)¶ Bases:
netconf.error._BadElementError
-
exception
netconf.error.
BadElementProtoError
(origmsg, element, **kwargs)¶ Bases:
netconf.error._BadElementError
-
exception
netconf.error.
ChannelClosed
¶
-
exception
netconf.error.
DataExistsAppError
(origmsg, **kwargs)¶ Bases:
netconf.error.RPCServerError
-
exception
netconf.error.
DataMissingAppError
(origmsg, **kwargs)¶ Bases:
netconf.error.RPCServerError
-
exception
netconf.error.
FramingError
¶
-
exception
netconf.error.
InvalidValueAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._InvalidValueError
-
exception
netconf.error.
InvalidValueProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._InvalidValueError
-
exception
netconf.error.
LockDeniedProtoError
(origmsg, session_id, **kwargs)¶ Bases:
netconf.error.RPCServerError
-
exception
netconf.error.
MalformedMessageRPCError
(origmsg)¶ Bases:
netconf.error.RPCServerError
If the server raises this exception the and netconf 1.0 is in use, the session will be closed
-
exception
netconf.error.
MissingAttributeAppError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._MissingAttributeError
-
exception
netconf.error.
MissingAttributeProtoError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._MissingAttributeError
-
exception
netconf.error.
MissingAttributeRPCError
(origmsg, element, attribute, **kwargs)¶ Bases:
netconf.error._MissingAttributeError
-
exception
netconf.error.
MissingElementAppError
(origmsg, tag, **kwargs)¶ Bases:
netconf.error._MissingElementError
-
exception
netconf.error.
MissingElementProtoError
(origmsg, tag, **kwargs)¶ Bases:
netconf.error._MissingElementError
-
exception
netconf.error.
NetconfError
(output, tree, error)¶ Bases:
netconf.error.NetconfException
-
get_error_info
()¶
-
get_error_severity
()¶
-
get_error_tag
()¶
-
get_error_type
()¶
-
-
exception
netconf.error.
NetconfException
¶ Bases:
Exception
-
exception
netconf.error.
OperationFailedAppError
(origmsg, etype, **kwargs)¶ Bases:
netconf.error._OperationFailedError
-
exception
netconf.error.
OperationFailedProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._OperationFailedError
-
exception
netconf.error.
OperationFailedRPCError
(origmsg, **kwargs)¶ Bases:
netconf.error._OperationFailedError
-
exception
netconf.error.
OperationNotSupportedAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._OperationNotSupportedError
-
exception
netconf.error.
OperationNotSupportedProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._OperationNotSupportedError
-
netconf.error.
RPCError
¶ alias of
netconf.error.NetconfError
-
exception
netconf.error.
RPCServerError
(origmsg, etype, tag, **kwargs)¶ Bases:
netconf.error.NetconfException
-
get_reply_msg
()¶
-
-
netconf.error.
RPCSvrBadElement
¶ alias of
netconf.error.BadElementAppError
-
netconf.error.
RPCSvrErrBadMsg
¶
-
netconf.error.
RPCSvrErrNotImpl
¶
-
exception
netconf.error.
RPCSvrException
(origmsg, exception, **kwargs)¶ Bases:
netconf.error.RPCServerError
-
netconf.error.
RPCSvrInvalidValue
¶ alias of
netconf.error.InvalidValueProtoError
-
netconf.error.
RPCSvrMissingElement
¶ alias of
netconf.error.MissingElementAppError
-
netconf.error.
RPCSvrUnknownElement
¶ alias of
netconf.error.UnknownElementAppError
-
exception
netconf.error.
ReplyTimeoutError
¶
-
exception
netconf.error.
ResourceDeniedAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._ResourceDeniedError
-
exception
netconf.error.
ResourceDeniedProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._ResourceDeniedError
-
exception
netconf.error.
ResourceDeniedRPCError
(origmsg, **kwargs)¶ Bases:
netconf.error._ResourceDeniedError
-
exception
netconf.error.
ResourceDeniedTransportError
(origmsg, **kwargs)¶ Bases:
netconf.error._ResourceDeniedError
-
exception
netconf.error.
RollbackFailedAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._RollbackFailedError
-
exception
netconf.error.
RollbackFailedProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._RollbackFailedError
-
exception
netconf.error.
SessionError
¶
-
netconf.error.
TimeoutError
¶ alias of
netconf.error.ReplyTimeoutError
-
exception
netconf.error.
TooBigAppError
(origmsg, **kwargs)¶ Bases:
netconf.error._TooBigError
-
exception
netconf.error.
TooBigProtoError
(origmsg, **kwargs)¶ Bases:
netconf.error._TooBigError
-
exception
netconf.error.
TooBigRPCError
(origmsg, **kwargs)¶ Bases:
netconf.error._TooBigError
-
exception
netconf.error.
TooBigTransportError
(origmsg, **kwargs)¶ Bases:
netconf.error._TooBigError
-
exception
netconf.error.
UnknownAttributeAppError
(origmsg, element, attribute, etype, **kwargs)¶ Bases:
netconf.error._UnknownAttributeError
-
exception
netconf.error.
UnknownAttributeProtoError
(origmsg, element, attribute, etype, **kwargs)¶ Bases:
netconf.error._UnknownAttributeError
-
exception
netconf.error.
UnknownAttributeRPCError
(origmsg, element, attribute, etype, **kwargs)¶ Bases:
netconf.error._UnknownAttributeError
-
exception
netconf.error.
UnknownElementAppError
(origmsg, element, **kwargs)¶ Bases:
netconf.error._UnknownElementError
-
exception
netconf.error.
UnknownElementProtoError
(origmsg, element, **kwargs)¶ Bases:
netconf.error._UnknownElementError
-
exception
netconf.error.
UnknownNamespaceAppError
(origmsg, element, etype, **kwargs)¶ Bases:
netconf.error._UnknownNamespaceError
-
exception
netconf.error.
UnknownNamespaceProtoError
(origmsg, element, etype, **kwargs)¶ Bases:
netconf.error._UnknownNamespaceError
The netconf.server
Module¶
-
class
netconf.server.
NetconfMethods
¶ Bases:
object
This is an abstract class that is used to document the server methods functionality.
The base server code will return not-implemented if the method is not found in the methods object, so feel free to use duck-typing here (i.e., no need to inherit). Create a class that implements the rpc_* methods you handle and pass that to NetconfSSHServer init.
-
nc_append_capabilities
(capabilities)¶ This method should append any capabilities it supports to capabilities
Parameters: capabilities (lxml.Element) – The element to append capability elements to. Returns: None
-
rpc_close_session
(session, rpc, *unused_params)¶
-
rpc_copy_config
(unused_session, rpc, *unused_params)¶ XXX API subject to change – unfinished
-
rpc_delete_config
(unused_session, rpc, *unused_params)¶ XXX API subject to change – unfinished
-
rpc_edit_config
(unused_session, rpc, *unused_params)¶ XXX API subject to change – unfinished
-
rpc_get
(session, rpc, filter_or_none)¶ Passed the filter element or None if not present
Parameters: - session (NetconfServerSession) – The server session with the client.
- rpc (lxml.Element) – The topmost element in the received message.
- filter_or_none (lxml.Element or None) – The filter element if present.
Returns: lxml.Element of “nc:data” type containing the requested state.
Raises: error.RPCServerError which will be used to construct an XML error response.
-
rpc_get_config
(session, rpc, source_elm, filter_or_none)¶ The client has requested the config state (config: true). The function is passed the source element and the filter element or None if not present
Parameters: - session (NetconfServerSession) – The server session with the client.
- rpc (lxml.Element) – The topmost element in the received message.
- source_elm (lxml.Element) – The source element indicating where the config should be drawn from.
- filter_or_none (lxml.Element or None) – The filter element if present.
Returns: lxml.Element of “nc:data” type containing the requested state.
Raises: error.RPCServerError which will be used to construct an XML error response.
-
rpc_kill_session
(session, rpc, *unused_params)¶
-
rpc_lock
(session, rpc, target)¶ Lock the given target datastore.
The server tracks the lock automatically which can be checked using the server is_locked method. This function is called after the lock is granted.
This server code can only verify if a lock has been granted or not, it cannot actually verify all the lock available conditions set forth in RFC6241. If any of the following can be true the user must also check this by implementing this function:
RFC6241:
A lock MUST NOT be granted if any of the following conditions is true:
- A lock is already held by any NETCONF session or another entity. ** The server checks for other sessions but cannot check if another entity (e.g., CLI) has been granted the lock.
- The target configuration is <candidate>, it has already been modified, and these changes have not been committed or rolled back. ** The server code cannot check this.
- The target configuration is <running>, and another NETCONF session has an ongoing confirmed commit (Section 8.4). ** The server code cannot check this.
Implement this method and if the lock should not be granted raise the following error (or anything else appropriate).
raise netconf.error.LockDeniedProtoError(rpc, <session-id-holding-lock>)Parameters: - session (NetconfServerSession) – The server session with the client.
- rpc (lxml.Element) – The topmost element in the received message.
- target – The tag name of the target child element indicating which config datastore should be locked.
Returns: None
Raises: error.RPCServerError which will be used to construct an XML error response. The lock will be released if an error is raised.
-
rpc_unlock
(session, rpc, target)¶ Unlock the given target datastore.
If this method raises an error the server code will not release the lock.
Parameters: - session (NetconfServerSession) – The server session with the client.
- rpc (lxml.Element or None) – The topmost element in the received message or None if the session is being closed and this is notification of lock release. In this latter case any exception raised will be ignored.
- target – The tag name of the target child element indicating which config datastore should be locked.
Returns: None
Raises: error.RPCServerError which will be used to construct an XML error response. The lock will be not be released if an error is raised.
-
-
class
netconf.server.
NetconfSSHServer
(server_ctl=None, server_methods=None, port=830, host_key=None, debug=False)¶ Bases:
sshutil.server.SSHServer
A netconf server.
Parameters: - server_ctl (ssh.ServerInterface) – The object used for authenticating connections to the server.
- server_methods – An object which implements servers the rpc_* methods.
- port – The port to bind the server to.
- host_key – The file containing the host key.
- debug – True to enable debug logging.
-
is_target_locked
(target)¶ Returns the sesions ID who owns the lock or 0 if not locked.
-
lock_target
(session, target)¶ Try to obtain target lock. Return 0 on success or the session ID of the lock holder.
-
unlock_target
(session, target)¶ Unlock the given target.
-
unlock_target_any
(session)¶ Unlock any targets locked by this session.
Returns list of targets that this session had locked.
-
class
netconf.server.
NetconfServerSession
(channel, server, unused_extra_args, debug)¶ Bases:
netconf.base.NetconfSession
Netconf Server-side session with a client.
This object will be passed to a the server RPC methods.
-
close
()¶ Close the servers side of the session.
-
handled_rpc_methods
= {'close-session', 'kill-session', 'lock', 'unlock'}¶
-
-
netconf.server.
SSHAuthController
¶
-
class
netconf.server.
SSHAuthorizedKeysController
(users=None)¶ Bases:
paramiko.server.ServerInterface
An implementation of paramiko ServerInterface that utilizes users authorized keys file for authentication.
Parameters: users – A list of usernames whose authorized keys will allow access. -
check_auth_none
(unused_username)¶ Determine if a client may open channels with no (further) authentication.
Return
AUTH_FAILED
if the client must authenticate, orAUTH_SUCCESSFUL
if it’s okay for the client to not authenticate.The default implementation always returns
AUTH_FAILED
.Parameters: username (str) – the username of the client. Returns: AUTH_FAILED
if the authentication fails;AUTH_SUCCESSFUL
if it succeeds.Return type: int
-
check_auth_password
(username, password)¶ Determine if a given username and password supplied by the client is acceptable for use in authentication.
Return
AUTH_FAILED
if the password is not accepted,AUTH_SUCCESSFUL
if the password is accepted and completes the authentication, orAUTH_PARTIALLY_SUCCESSFUL
if your authentication is stateful, and this key is accepted for authentication, but more authentication is required. (In this latter case, get_allowed_auths will be called to report to the client what options it has for continuing the authentication.)The default implementation always returns
AUTH_FAILED
.Parameters: - username (str) – the username of the authenticating client.
- password (str) – the password given by the client.
Returns: AUTH_FAILED
if the authentication fails;AUTH_SUCCESSFUL
if it succeeds;AUTH_PARTIALLY_SUCCESSFUL
if the password auth is successful, but authentication must continue.Return type: int
-
check_auth_publickey
(username, key)¶ Determine if a given key supplied by the client is acceptable for use in authentication. You should override this method in server mode to check the username and key and decide if you would accept a signature made using this key.
Return
AUTH_FAILED
if the key is not accepted,AUTH_SUCCESSFUL
if the key is accepted and completes the authentication, orAUTH_PARTIALLY_SUCCESSFUL
if your authentication is stateful, and this password is accepted for authentication, but more authentication is required. (In this latter case, get_allowed_auths will be called to report to the client what options it has for continuing the authentication.)Note that you don’t have to actually verify any key signtature here. If you’re willing to accept the key, Paramiko will do the work of verifying the client’s signature.
The default implementation always returns
AUTH_FAILED
.Parameters: - username (str) – the username of the authenticating client
- key (PKey) – the key object provided by the client
Returns: AUTH_FAILED
if the client can’t authenticate with this key;AUTH_SUCCESSFUL
if it can;AUTH_PARTIALLY_SUCCESSFUL
if it can authenticate with this key but must continue with authenticationReturn type: int
-
check_channel_request
(kind, chanid)¶ Determine if a channel request of a given type will be granted, and return
OPEN_SUCCEEDED
or an error code. This method is called in server mode when the client requests a channel, after authentication is complete.If you allow channel requests (and an ssh server that didn’t would be useless), you should also override some of the channel request methods below, which are used to determine which services will be allowed on a given channel:
- check_channel_pty_request
- check_channel_shell_request
- check_channel_subsystem_request
- check_channel_window_change_request
- check_channel_x11_request
- check_channel_forward_agent_request
The
chanid
parameter is a small number that uniquely identifies the channel within a .Transport. A .Channel object is not created unless this method returnsOPEN_SUCCEEDED
– once a .Channel object is created, you can call .Channel.get_id to retrieve the channel ID.The return value should either be
OPEN_SUCCEEDED
(or0
) to allow the channel request, or one of the following error codes to reject it:OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
OPEN_FAILED_CONNECT_FAILED
OPEN_FAILED_UNKNOWN_CHANNEL_TYPE
OPEN_FAILED_RESOURCE_SHORTAGE
The default implementation always returns
OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
.Parameters: - kind (str) – the kind of channel the client would like to open (usually
"session"
). - chanid (int) – ID of the channel
Returns: an int success or failure code (listed above)
-
check_channel_subsystem_request
(channel, name)¶ Determine if a requested subsystem will be provided to the client on the given channel. If this method returns
True
, all future I/O through this channel will be assumed to be connected to the requested subsystem. An example of a subsystem issftp
.The default implementation checks for a subsystem handler assigned via .Transport.set_subsystem_handler. If one has been set, the handler is invoked and this method returns
True
. Otherwise it returnsFalse
.Note
Because the default implementation uses the .Transport to identify valid subsystems, you probably won’t need to override this method.
Parameters: - channel (Channel) – the .Channel the pty request arrived on.
- name (str) – name of the requested subsystem.
Returns: True
if this channel is now hooked up to the requested subsystem;False
if that subsystem can’t or won’t be provided.
-
get_allowed_auths
(username)¶ Return a list of authentication methods supported by the server. This list is sent to clients attempting to authenticate, to inform them of authentication methods that might be successful.
The “list” is actually a string of comma-separated names of types of authentication. Possible values are
"password"
,"publickey"
, and"none"
.The default implementation always returns
"password"
.Parameters: username (str) – the username requesting authentication. Returns: a comma-separated str of authentication types
-
get_user_auth_keys
(username)¶ Parse the users’s authorized_keys file if any to look for authorized keys
-
-
class
netconf.server.
SSHUserPassController
(username=None, password=None)¶ Bases:
paramiko.server.ServerInterface
An implementation of paramiko ServerInterface that authorizes a single user and password.
Parameters: - username – The username to allow.
- password – The password to allow.
-
check_auth_none
(username)¶ Determine if a client may open channels with no (further) authentication.
Return
AUTH_FAILED
if the client must authenticate, orAUTH_SUCCESSFUL
if it’s okay for the client to not authenticate.The default implementation always returns
AUTH_FAILED
.Parameters: username (str) – the username of the client. Returns: AUTH_FAILED
if the authentication fails;AUTH_SUCCESSFUL
if it succeeds.Return type: int
-
check_auth_password
(username, password)¶ Determine if a given username and password supplied by the client is acceptable for use in authentication.
Return
AUTH_FAILED
if the password is not accepted,AUTH_SUCCESSFUL
if the password is accepted and completes the authentication, orAUTH_PARTIALLY_SUCCESSFUL
if your authentication is stateful, and this key is accepted for authentication, but more authentication is required. (In this latter case, get_allowed_auths will be called to report to the client what options it has for continuing the authentication.)The default implementation always returns
AUTH_FAILED
.Parameters: - username (str) – the username of the authenticating client.
- password (str) – the password given by the client.
Returns: AUTH_FAILED
if the authentication fails;AUTH_SUCCESSFUL
if it succeeds;AUTH_PARTIALLY_SUCCESSFUL
if the password auth is successful, but authentication must continue.Return type: int
-
check_channel_request
(kind, chanid)¶ Determine if a channel request of a given type will be granted, and return
OPEN_SUCCEEDED
or an error code. This method is called in server mode when the client requests a channel, after authentication is complete.If you allow channel requests (and an ssh server that didn’t would be useless), you should also override some of the channel request methods below, which are used to determine which services will be allowed on a given channel:
- check_channel_pty_request
- check_channel_shell_request
- check_channel_subsystem_request
- check_channel_window_change_request
- check_channel_x11_request
- check_channel_forward_agent_request
The
chanid
parameter is a small number that uniquely identifies the channel within a .Transport. A .Channel object is not created unless this method returnsOPEN_SUCCEEDED
– once a .Channel object is created, you can call .Channel.get_id to retrieve the channel ID.The return value should either be
OPEN_SUCCEEDED
(or0
) to allow the channel request, or one of the following error codes to reject it:OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
OPEN_FAILED_CONNECT_FAILED
OPEN_FAILED_UNKNOWN_CHANNEL_TYPE
OPEN_FAILED_RESOURCE_SHORTAGE
The default implementation always returns
OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
.Parameters: - kind (str) – the kind of channel the client would like to open (usually
"session"
). - chanid (int) – ID of the channel
Returns: an int success or failure code (listed above)
-
check_channel_subsystem_request
(channel, name)¶ Determine if a requested subsystem will be provided to the client on the given channel. If this method returns
True
, all future I/O through this channel will be assumed to be connected to the requested subsystem. An example of a subsystem issftp
.The default implementation checks for a subsystem handler assigned via .Transport.set_subsystem_handler. If one has been set, the handler is invoked and this method returns
True
. Otherwise it returnsFalse
.Note
Because the default implementation uses the .Transport to identify valid subsystems, you probably won’t need to override this method.
Parameters: - channel (Channel) – the .Channel the pty request arrived on.
- name (str) – name of the requested subsystem.
Returns: True
if this channel is now hooked up to the requested subsystem;False
if that subsystem can’t or won’t be provided.
-
get_allowed_auths
(username)¶ Return a list of authentication methods supported by the server. This list is sent to clients attempting to authenticate, to inform them of authentication methods that might be successful.
The “list” is actually a string of comma-separated names of types of authentication. Possible values are
"password"
,"publickey"
, and"none"
.The default implementation always returns
"password"
.Parameters: username (str) – the username requesting authentication. Returns: a comma-separated str of authentication types
The netconf.util
Module¶
-
netconf.util.
elm
(tag, attrib=None, **extra)¶ Create an lxml.etree.Element using qname to obtain the tag.
This is a replacement for calling lxml.etree.Element directly that supports prefixed tags.
Parameters: - tag – A possibly prefixed tag.
- attrib – Attributes for the element.
- extra – extra parameters see lxml.etree.Element.
Returns: lxml.etree.Element.
-
netconf.util.
filter_containment_iter
(fcontain_elm, dest_node, containment_nodes, leaf_elms, append_to)¶ Given a containment filter node (or None) verify that all leaf elements either match, have corresponding selection nodes (empty) or are not present.
If all leaf criteria are met then the iterator will return a triple of (new_filter_node, new_dest_node, new_data). new_filter_node corresponds to the matched containment node which is returned in new_dest_node, and new_data will be an element corresponding to the passed in dest_node.
These should be processed by calling filter_containment_iter again.
Additionally the correct leaf data will be added to dest_node, and dest_node will be appended to append_to if append_to is not None.
This implements RFC6241 section 6.2.5
-
netconf.util.
filter_leaf_allows
(filter_elm, xpath, value)¶ Check the value at the xpath specified leaf matches the value.
- If filter_elm is None then allow.
- If there is no xpath element then allow if there are no other children.
- XXX what about xpath that has embedded predicates! perhaps what we want to call this is a normal path not an xpath.
-
netconf.util.
filter_leaf_allows_add
(filter_elm, tag, data, value)¶
-
netconf.util.
filter_leaf_values
(fcontain_elm, dest_node, leaf_elms, append_to)¶ Given a containment element (or None) verify that all leaf elements in leaf_elms either match, have corresponding selection nodes (empty) or are not present.
Additionally the correct leaf data will be added to dest_node, and dest_node will be appended to append_to if append_to is not None.
The return value with be True, False, or a possibly empty set of selection/containment nodes The only failing value is False, if True is returned then the caller should include all containment sibling nodes, otherwise the caller should process the list of containment/selection nodes.
-
netconf.util.
filter_list_iter
(filter_list, key_xpath, keys)¶ Return key, elm pairs that are allowed by keys using the values found using the given key_xpath
-
netconf.util.
filter_node_match
(filter_node, match_elm)¶ Given a filter node element and a nodename and attribute dictionary return true if the filter element matches the elmname, attributes and value (if not None).
The filter element can use a wildcard namespace or a specific namespace the attributes can be missing from the filter node but otherwise must match and the value is only checked for a match if it is not None.
-
netconf.util.
filter_node_match_no_value
(filter_node, match_elm)¶
-
netconf.util.
filter_results
(rpc, data, filter_or_none, debug=False)¶ Check for a user filter and prune the result data accordingly.
Parameters: - rpc – An RPC message element.
- data – The data to filter.
- filter_or_none (lxml.Element) – Filter element or None.
-
netconf.util.
filter_tag_match
(filter_tag, elm_tag)¶
-
netconf.util.
filter_to_xpath
(felm)¶ Convert a filter sub-tree to an xpath expression.
Parameters: felm – A subtree-filter XML sub-tree. Returns str: An xpath expression equivalent to the sub-tree.
-
netconf.util.
is_selection_node
(felm)¶
-
netconf.util.
leaf
(tag, value, attrib=None, **extra)¶ Create an lxml.etree.Element leaf node using qname to obtain the tag.
This is a replacement for calling lxml.etree.Element directly that supports prefixed tags.
Parameters: - tag – A possibly prefixed tag.
- value – Value for text of element.
- attrib – Attributes for the element.
- extra – extra parameters see lxml.etree.Element.
Returns: lxml.etree.Element.
-
netconf.util.
leaf_elm
(tag, value, attrib=None, **extra)¶ Create an lxml.etree.Element leaf node using qname to obtain the tag.
This is a replacement for calling lxml.etree.Element directly that supports prefixed tags.
Parameters: - tag – A possibly prefixed tag.
- value – Value for text of element.
- attrib – Attributes for the element.
- extra – extra parameters see lxml.etree.Element.
Returns: lxml.etree.Element.
-
netconf.util.
qname
(tag)¶ Return a qualified tag name (i.e. {namespace}localtag)
Handles prefix notation by looking up in global dictionary.
Parameters: tag – A possibly prefixed tag. Returns: Fully qualified tag name (lxml.etree.QName).
-
netconf.util.
subelm
(pelm, tag, attrib=None, **extra)¶ Create an child lxml.etree.Element using qname to obtain the tag.
This is a replacement for calling lxml.etree.SubElement directly that supports prefixed tags.
Parameters: - pelm – The parent element.
- tag – A possibly prefixed tag.
- attrib – Attributes for the element.
- extra – extra parameters see lxml.etree.SubElement.
Returns: lxml.etree.Element.
-
netconf.util.
xpath_filter_result
(data, xpath)¶ Filter a result given an xpath expression.
Parameters: - data – The nc:data result element.
- xpath – The xpath expression string.
Returns: New nc:data result element pruned by the xpath expression.
>>> xml = ''' ... <data> ... <devs> ... <dev> ... <name>dev1</name> ... <slots>1</slots> ... </dev> ... <dev> ... <name>dev2</name> ... <slots>2</slots> ... </dev> ... <dev> ... <name>dev3</name> ... <slots>3</slots> ... </dev> ... </devs> ... </data> ... ''' >>> data = etree.fromstring(xml.replace(' ', '').replace('\n', '')) >>> result = xpath_filter_result(data, "/devs/dev") >>> etree.tounicode(result) '<data><devs><dev><name>dev1</name><slots>1</slots></dev><dev><name>dev2</name><slots>2</slots></dev><dev><name>dev3</name><slots>3</slots></dev></devs></data>' >>> result = xpath_filter_result(data, "/devs/dev[name='dev1']") >>> etree.tounicode(result) '<data><devs><dev><name>dev1</name><slots>1</slots></dev></devs></data>' >>> result = xpath_filter_result(data, "/devs/dev[name='dev2']") >>> etree.tounicode(result) '<data><devs><dev><name>dev2</name><slots>2</slots></dev></devs></data>' >>> result = xpath_filter_result(data, "/devs/dev[name='dev2'] | /devs/dev[name='dev1']") >>> etree.tounicode(result) '<data><devs><dev><name>dev1</name><slots>1</slots></dev><dev><name>dev2</name><slots>2</slots></dev></devs></data>' >>> result = xpath_filter_result(data, "/devs/dev[name='dev1'] | /devs/dev[name='dev2']") >>> etree.tounicode(result) '<data><devs><dev><name>dev1</name><slots>1</slots></dev><dev><name>dev2</name><slots>2</slots></dev></devs></data>' >>> result = xpath_filter_result(data, "/devs/dev[name='dev1'] | /devs/dev[slots='2']") >>> etree.tounicode(result) '<data><devs><dev><name>dev1</name><slots>1</slots></dev><dev><name>dev2</name><slots>2</slots></dev></devs></data>'