0
# Transport Layer
1
2
Low-level transport implementations providing the communication foundation for NETCONF sessions. NCClient supports multiple transport protocols with connection multiplexing, session management, and protocol-specific optimizations.
3
4
## Capabilities
5
6
### Base Transport Classes
7
8
Foundation classes providing common transport functionality and interfaces.
9
10
```python { .api }
11
class Session:
12
"""Base transport session class providing common functionality."""
13
14
def connect(self, *args, **kwargs):
15
"""Establish transport connection."""
16
17
def close(self):
18
"""Close transport connection."""
19
20
@property
21
def connected(self):
22
"""bool: Connection status."""
23
24
@property
25
def id(self):
26
"""str: Session ID assigned by server."""
27
28
def send(self, message):
29
"""Send message over transport."""
30
31
def take_notification(self, block=True, timeout=None):
32
"""Retrieve notification from queue."""
33
34
class SessionListener:
35
"""Interface for session event handling."""
36
37
def callback(self, root, raw):
38
"""Handle received message callback."""
39
40
def errback(self, ex):
41
"""Handle error callback."""
42
43
class NetconfBase:
44
"""Base NETCONF protocol functionality."""
45
```
46
47
### SSH Transport
48
49
Primary transport implementation using SSH for secure NETCONF communication.
50
51
```python { .api }
52
class SSHSession(Session):
53
"""SSH transport session with NETCONF over SSH subsystem."""
54
55
def __init__(self, device_handler):
56
"""
57
Initialize SSH session.
58
59
Parameters:
60
- device_handler: device-specific handler
61
"""
62
63
def connect(self, host, port=830, timeout=None,
64
username=None, password=None, key_filename=None,
65
allow_agent=True, hostkey_verify=True,
66
look_for_keys=True, sock=None):
67
"""
68
Connect via SSH transport.
69
70
Parameters:
71
- host: str, hostname or IP address
72
- port: int, SSH port (default 830)
73
- timeout: float, connection timeout
74
- username: str, SSH username
75
- password: str, SSH password
76
- key_filename: str or list, SSH private key file(s)
77
- allow_agent: bool, use SSH agent
78
- hostkey_verify: bool, verify host key
79
- look_for_keys: bool, search for SSH keys
80
- sock: socket, existing socket connection
81
"""
82
83
def scp(self):
84
"""Create SCP client for file transfer."""
85
86
@property
87
def transport(self):
88
"""SSH transport object."""
89
```
90
91
### LibSSH Transport
92
93
Alternative SSH implementation using ssh-python library for enhanced performance.
94
95
```python { .api }
96
class LibSSHSession(Session):
97
"""LibSSH-based transport session (requires ssh-python)."""
98
99
def __init__(self, device_handler):
100
"""
101
Initialize LibSSH session.
102
103
Parameters:
104
- device_handler: device-specific handler
105
"""
106
107
def connect(self, host, port=830, username=None,
108
password=None, **kwargs):
109
"""
110
Connect via LibSSH transport.
111
112
Parameters:
113
- host: str, hostname or IP address
114
- port: int, SSH port (default 830)
115
- username: str, SSH username
116
- password: str, SSH password
117
"""
118
```
119
120
### TLS Transport
121
122
Secure transport implementation using TLS for NETCONF over TLS communication.
123
124
```python { .api }
125
class TLSSession(Session):
126
"""TLS transport session for NETCONF over TLS."""
127
128
def __init__(self, device_handler):
129
"""
130
Initialize TLS session.
131
132
Parameters:
133
- device_handler: device-specific handler
134
"""
135
136
def connect(self, host, port=6513, certfile=None,
137
keyfile=None, ca_certs=None, cert_reqs=None,
138
ssl_version=None, ciphers=None, **kwargs):
139
"""
140
Connect via TLS transport.
141
142
Parameters:
143
- host: str, hostname or IP address
144
- port: int, TLS port (default 6513)
145
- certfile: str, client certificate file
146
- keyfile: str, client private key file
147
- ca_certs: str, CA certificates file
148
- cert_reqs: int, certificate verification requirements
149
- ssl_version: int, SSL/TLS protocol version
150
- ciphers: str, cipher suite specification
151
"""
152
```
153
154
### Unix Domain Socket Transport
155
156
Local transport implementation using Unix domain sockets (Unix platforms only).
157
158
```python { .api }
159
class UnixSocketSession(Session):
160
"""Unix domain socket transport session."""
161
162
def __init__(self, device_handler):
163
"""
164
Initialize Unix socket session.
165
166
Parameters:
167
- device_handler: device-specific handler
168
"""
169
170
def connect(self, path, **kwargs):
171
"""
172
Connect via Unix domain socket.
173
174
Parameters:
175
- path: str, socket file path
176
"""
177
```
178
179
## Transport Errors
180
181
Exception hierarchy for transport-specific error conditions.
182
183
```python { .api }
184
class TransportError(NCClientError):
185
"""Base exception for transport layer errors."""
186
187
class AuthenticationError(TransportError):
188
"""Authentication failure during transport setup."""
189
190
class SessionCloseError(TransportError):
191
"""Error during session close operation."""
192
193
class SSHError(TransportError):
194
"""SSH transport specific error."""
195
196
class SSHUnknownHostError(SSHError):
197
"""SSH unknown host key error."""
198
```
199
200
## Protocol Support
201
202
### NETCONF Protocol Features
203
204
```python { .api }
205
# NETCONF base capabilities
206
NETCONF_BASE_10 = "urn:ietf:params:netconf:base:1.0"
207
NETCONF_BASE_11 = "urn:ietf:params:netconf:base:1.1"
208
209
# Chunked framing support (NETCONF 1.1)
210
def supports_chunked_framing(capabilities):
211
"""Check if server supports chunked framing."""
212
213
# EOM framing support (NETCONF 1.0)
214
def supports_eom_framing(capabilities):
215
"""Check if server supports end-of-message framing."""
216
```
217
218
### Message Parsing
219
220
```python { .api }
221
class Parser:
222
"""NETCONF message parser for framing and XML processing."""
223
224
def __init__(self, session):
225
"""Initialize parser for session."""
226
227
def parse(self, data):
228
"""Parse incoming NETCONF message data."""
229
230
class DefaultParser(Parser):
231
"""Standard NETCONF message parser."""
232
233
class ChunkedFramingParser(Parser):
234
"""Parser for NETCONF 1.1 chunked framing."""
235
```
236
237
### Notification Handling
238
239
```python { .api }
240
class NotificationListener:
241
"""Handles NETCONF event notifications."""
242
243
def __init__(self, session):
244
"""Initialize notification listener."""
245
246
def add_listener(self, callback):
247
"""Add notification callback."""
248
249
def remove_listener(self, callback):
250
"""Remove notification callback."""
251
252
class Notification:
253
"""NETCONF event notification."""
254
255
@property
256
def event_time(self):
257
"""str: Notification timestamp."""
258
259
@property
260
def notification_xml(self):
261
"""str: Notification content as XML."""
262
```
263
264
## Usage Examples
265
266
### Direct SSH Transport Usage
267
268
```python
269
from ncclient.transport import SSHSession
270
from ncclient.devices.default import DefaultDeviceHandler
271
272
# Create device handler
273
device_handler = DefaultDeviceHandler({}, [])
274
275
# Initialize SSH session
276
session = SSHSession(device_handler)
277
278
try:
279
# Connect with SSH parameters
280
session.connect(
281
host='192.168.1.1',
282
port=830,
283
username='netconf-user',
284
password='netconf-pass',
285
hostkey_verify=False,
286
timeout=30
287
)
288
289
print(f"Connected with session ID: {session.id}")
290
print(f"Connection status: {session.connected}")
291
292
finally:
293
session.close()
294
```
295
296
### TLS Transport with Certificates
297
298
```python
299
from ncclient.transport import TLSSession
300
from ncclient.devices.default import DefaultDeviceHandler
301
302
device_handler = DefaultDeviceHandler({}, [])
303
session = TLSSession(device_handler)
304
305
try:
306
session.connect(
307
host='secure-device.example.com',
308
port=6513,
309
certfile='/path/to/client.crt',
310
keyfile='/path/to/client.key',
311
ca_certs='/path/to/ca.crt'
312
)
313
314
print("Secure TLS connection established")
315
316
finally:
317
session.close()
318
```
319
320
### Unix Socket Transport
321
322
```python
323
from ncclient.transport import UnixSocketSession
324
from ncclient.devices.default import DefaultDeviceHandler
325
import sys
326
327
# Unix sockets not available on Windows
328
if sys.platform != 'win32':
329
device_handler = DefaultDeviceHandler({}, [])
330
session = UnixSocketSession(device_handler)
331
332
try:
333
session.connect(path='/var/run/netconf.sock')
334
print("Connected via Unix domain socket")
335
finally:
336
session.close()
337
```
338
339
### Custom Session Listener
340
341
```python
342
from ncclient.transport import SessionListener
343
from ncclient import manager
344
345
class MySessionListener(SessionListener):
346
def callback(self, root, raw):
347
print(f"Received message: {raw[:100]}...")
348
349
def errback(self, ex):
350
print(f"Session error: {ex}")
351
352
# Use with manager (implementation detail)
353
listener = MySessionListener()
354
```
355
356
### Error Handling
357
358
```python
359
from ncclient.transport import (
360
TransportError, AuthenticationError,
361
SSHError, SSHUnknownHostError
362
)
363
364
try:
365
with manager.connect_ssh(
366
host='untrusted-device.example.com',
367
username='admin',
368
password='admin',
369
hostkey_verify=True
370
) as m:
371
pass
372
373
except SSHUnknownHostError as e:
374
print("Unknown host key - add to known_hosts")
375
except AuthenticationError as e:
376
print("Authentication failed - check credentials")
377
except SSHError as e:
378
print(f"SSH error: {e}")
379
except TransportError as e:
380
print(f"Transport error: {e}")
381
```