0
# Connection Management
1
2
Functions for establishing and managing NETCONF sessions over various transport protocols. NCClient provides flexible connection methods with support for device-specific parameters, authentication methods, and transport customization.
3
4
## Capabilities
5
6
### Generic Connection
7
8
Automatically selects appropriate transport (typically SSH) based on parameters provided.
9
10
```python { .api }
11
def connect(host=None, port=830, username=None, password=None,
12
key_filename=None, timeout=None, device_params=None,
13
manager_params=None, nc_params=None, errors_params=None,
14
**kwargs):
15
"""
16
Initialize a Manager over automatically selected transport.
17
18
Parameters:
19
- host: str, hostname or IP address
20
- port: int, NETCONF port (default 830)
21
- username: str, username for authentication
22
- password: str, password for authentication
23
- key_filename: str, path to private key file
24
- timeout: float, connection timeout in seconds
25
- device_params: dict, device-specific parameters
26
- manager_params: dict, manager configuration
27
- nc_params: dict, NETCONF protocol parameters
28
- errors_params: dict, error handling configuration
29
- hostkey_verify: bool, verify host key (default True)
30
- allow_agent: bool, use SSH agent (default True)
31
- look_for_keys: bool, look for key files (default True)
32
- use_libssh: bool, use LibSSH transport (default False)
33
34
Returns:
35
Manager: NETCONF session manager instance
36
"""
37
```
38
39
### SSH Connection
40
41
Establishes NETCONF session over SSH transport with full SSH client capabilities.
42
43
```python { .api }
44
def connect_ssh(host, port=830, username=None, password=None,
45
key_filename=None, timeout=None, allow_agent=True,
46
hostkey_verify=True, look_for_keys=True,
47
sock=None, **kwargs):
48
"""
49
Initialize a Manager over SSH transport.
50
51
Parameters:
52
- host: str, hostname or IP address
53
- port: int, SSH port (default 830)
54
- username: str, SSH username
55
- password: str, SSH password
56
- key_filename: str or list, SSH private key file(s)
57
- timeout: float, connection timeout
58
- allow_agent: bool, use SSH agent for authentication
59
- hostkey_verify: bool, verify SSH host key
60
- look_for_keys: bool, search for SSH keys in standard locations
61
- sock: socket, existing socket connection
62
63
Returns:
64
Manager: SSH-based NETCONF session manager
65
"""
66
```
67
68
### LibSSH Connection
69
70
Alternative SSH implementation using ssh-python library for enhanced performance.
71
72
```python { .api }
73
def connect_libssh(host, port=830, username=None, password=None,
74
**kwargs):
75
"""
76
Initialize a Manager over LibSSH transport.
77
Requires 'ssh-python' package to be installed.
78
79
Parameters:
80
- host: str, hostname or IP address
81
- port: int, SSH port (default 830)
82
- username: str, SSH username
83
- password: str, SSH password
84
85
Returns:
86
Manager: LibSSH-based NETCONF session manager
87
"""
88
```
89
90
### TLS Connection
91
92
Establishes NETCONF session over TLS transport for secure communication.
93
94
```python { .api }
95
def connect_tls(host, port=6513, certfile=None, keyfile=None,
96
ca_certs=None, cert_reqs=None, ssl_version=None,
97
ciphers=None, **kwargs):
98
"""
99
Initialize a Manager over TLS transport.
100
101
Parameters:
102
- host: str, hostname or IP address
103
- port: int, TLS port (default 6513)
104
- certfile: str, client certificate file
105
- keyfile: str, client private key file
106
- ca_certs: str, CA certificates file
107
- cert_reqs: int, certificate requirements
108
- ssl_version: int, SSL protocol version
109
- ciphers: str, cipher specification
110
111
Returns:
112
Manager: TLS-based NETCONF session manager
113
"""
114
```
115
116
### Unix Domain Socket Connection
117
118
Connects to NETCONF server via Unix domain socket (Unix platforms only).
119
120
```python { .api }
121
def connect_uds(path, **kwargs):
122
"""
123
Initialize a Manager over Unix domain socket transport.
124
125
Parameters:
126
- path: str, path to Unix domain socket
127
128
Returns:
129
Manager: Unix socket-based NETCONF session manager
130
"""
131
```
132
133
### Call Home Connection
134
135
Handles NETCONF call-home connections where the device initiates the connection.
136
137
```python { .api }
138
def call_home(host, port=4334, timeout=10, **kwargs):
139
"""
140
Handle NETCONF call-home connection.
141
142
Parameters:
143
- host: str, interface to bind and listen on
144
- port: int, port to listen on (default 4334)
145
- timeout: int, connection timeout in seconds
146
147
Returns:
148
Manager: Call-home NETCONF session manager
149
"""
150
```
151
152
### Device Handler Creation
153
154
Creates device-specific handlers for vendor optimizations and customizations.
155
156
```python { .api }
157
def make_device_handler(device_params, ignore_errors=None):
158
"""
159
Create device handler for vendor-specific functionality.
160
161
Parameters:
162
- device_params: dict, device configuration including 'name' key
163
- ignore_errors: list, error patterns to ignore
164
165
Returns:
166
DeviceHandler: Device-specific handler instance
167
"""
168
```
169
170
## Manager Class
171
172
The Manager class provides the main interface for NETCONF operations and session management.
173
174
```python { .api }
175
class Manager:
176
"""
177
Main NETCONF session manager providing operation dispatch and session control.
178
Supports context manager protocol for automatic session cleanup.
179
"""
180
181
def __init__(self, session, device_handler, timeout=30,
182
raise_mode=operations.RaiseMode.ALL):
183
"""
184
Initialize Manager instance.
185
186
Parameters:
187
- session: transport session instance
188
- device_handler: device-specific handler
189
- timeout: default operation timeout in seconds
190
- raise_mode: error raising behavior
191
"""
192
193
def __enter__(self):
194
"""Context manager entry."""
195
196
def __exit__(self, *args):
197
"""Context manager exit with session cleanup."""
198
199
def locked(self, target):
200
"""
201
Create lock context manager for datastore.
202
203
Parameters:
204
- target: str, datastore name ('running', 'candidate', 'startup')
205
206
Returns:
207
LockContext: Context manager for datastore locking
208
"""
209
210
def take_notification(self, block=True, timeout=None):
211
"""
212
Retrieve notification from queue.
213
214
Parameters:
215
- block: bool, whether to block waiting for notification
216
- timeout: float, timeout in seconds
217
218
Returns:
219
Notification or None: Retrieved notification object
220
"""
221
222
@property
223
def client_capabilities(self):
224
"""Capabilities: Client NETCONF capabilities."""
225
226
@property
227
def server_capabilities(self):
228
"""Capabilities: Server NETCONF capabilities."""
229
230
@property
231
def session_id(self):
232
"""str: NETCONF session ID."""
233
234
@property
235
def connected(self):
236
"""bool: Connection status."""
237
238
@property
239
def timeout(self):
240
"""float: Default operation timeout."""
241
242
@timeout.setter
243
def timeout(self, value):
244
"""Set default operation timeout."""
245
246
@property
247
def async_mode(self):
248
"""bool: Asynchronous operation mode."""
249
250
@async_mode.setter
251
def async_mode(self, mode):
252
"""Set asynchronous operation mode."""
253
254
@property
255
def raise_mode(self):
256
"""RaiseMode: Error raising behavior."""
257
258
@raise_mode.setter
259
def raise_mode(self, mode):
260
"""Set error raising behavior."""
261
262
@property
263
def huge_tree(self):
264
"""bool: Large XML tree support."""
265
266
@huge_tree.setter
267
def huge_tree(self, enabled):
268
"""Enable/disable large XML tree support."""
269
```
270
271
## Usage Examples
272
273
### Basic SSH Connection
274
275
```python
276
from ncclient import manager
277
278
# Simple SSH connection
279
with manager.connect_ssh(
280
host='192.168.1.1',
281
username='admin',
282
password='admin',
283
hostkey_verify=False
284
) as m:
285
print(f"Connected to session: {m.session_id}")
286
print("Server capabilities:")
287
for cap in m.server_capabilities:
288
print(f" {cap}")
289
```
290
291
### Device-Specific Connection
292
293
```python
294
from ncclient import manager
295
296
# Junos device with specific parameters
297
device_params = {
298
'name': 'junos',
299
'local': False
300
}
301
302
with manager.connect_ssh(
303
host='juniper-router.example.com',
304
username='netconf-user',
305
key_filename='/path/to/private/key',
306
device_params=device_params
307
) as m:
308
# Device-specific operations available
309
pass
310
```
311
312
### Connection with Error Handling
313
314
```python
315
from ncclient import manager
316
from ncclient.operations import RaiseMode
317
318
# Configure error handling
319
errors_params = {
320
'ignore_errors': ['warning'],
321
'raise_mode': RaiseMode.ERRORS
322
}
323
324
manager_params = {
325
'timeout': 60
326
}
327
328
with manager.connect_ssh(
329
host='device.example.com',
330
username='admin',
331
password='admin',
332
errors_params=errors_params,
333
manager_params=manager_params
334
) as m:
335
# Operations with custom error handling
336
pass
337
```