Debian Codegraph @

lib/jnpr/junos/device.py

raw
1 # stdlib
2 import os
3 import six
4 import types
5 import platform
6 import warnings
7 import logging
8
9 # stdlib, in support of the the 'probe' method
10 import socket
11 import datetime
12 import time
13 import sys
14 import json
15 import re
16
17 # 3rd-party packages
18 from lxml import etree
19 from ncclient import manager as netconf_ssh
20 import ncclient.transport.errors as NcErrors
21 from ncclient.transport.session import SessionListener
22 import ncclient.operations.errors as NcOpErrors
23 from ncclient.operations import RPCError
24 import paramiko
25 import jinja2
26
27 # local modules
28 from jnpr.junos.rpcmeta import _RpcMetaExec
29 from jnpr.junos import exception as EzErrors
30 from jnpr.junos.factcache import _FactCache
31 from jnpr.junos.ofacts import *
32 from jnpr.junos import jxml as JXML
33 from jnpr.junos.decorators import (
34 timeoutDecorator,
35 normalizeDecorator,
36 ignoreWarnDecorator,
37 )
38 from jnpr.junos.exception import JSONLoadError, ConnectError
39
40 # check for ncclient support for filter_xml. Remove these changes once ncclient
41 # release filter_xml/SAX parsing feature
42 # https://github.com/ncclient/ncclient/pull/324
43 from ncclient.operations.third_party.juniper.rpc import ExecuteRpc
44 import inspect
45
46 if sys.version_info[0] >= 3:
47 NCCLIENT_FILTER_XML = len(inspect.signature(ExecuteRpc.request).parameters) == 3
48 else:
49 NCCLIENT_FILTER_XML = len(inspect.getargspec(ExecuteRpc.request).args) == 3
50
51 _MODULEPATH = os.path.dirname(__file__)
52
53 logger = logging.getLogger("jnpr.junos.device")
54
55
56 class _MyTemplateLoader(jinja2.BaseLoader):
57 """
58 Create a jinja2 template loader class that can be used to
59 load templates from all over the filesystem, but defaults
60 to the CWD and the 'templates' directory of the module
61 """
62
63 def __init__(self):
64 self.paths = [".", os.path.join(_MODULEPATH, "templates")]
65
66 def get_source(self, environment, template):
67 def _in_path(dir):
68 return os.path.exists(os.path.join(dir, template))
69
70 path = list(filter(_in_path, self.paths))
71 if not path:
72 raise jinja2.TemplateNotFound(template)
73
74 path = os.path.join(path[0], template)
75 mtime = os.path.getmtime(path)
76 with open(path) as f:
77 # You are trying to decode an object that is already decoded.
78 # You have a str, there is no need to decode from UTF-8 anymore.
79 # open already decodes to Unicode in Python 3 if you open in text
80 # mode. If you want to open it as bytes, so that you can then
81 # decode, you need to open with mode 'rb'.
82 source = f.read()
83 return source, path, lambda: mtime == os.path.getmtime(path)
84
85
86 _Jinja2ldr = jinja2.Environment(loader=_MyTemplateLoader())
87
88
89 class _Connection(object):
90 ON_JUNOS = (
91 platform.system().upper() == "JUNOS"
92 or platform.release().startswith("JNPR")
93 or os.path.isfile("/usr/share/cevo/cevo_version")
94 )
95
96 # for juniper specific containers likes crpd, cmgd, cbng
97 # and similar entities, we will need to check the product.conf
98 # file for on-box implementation
99
100 if ON_JUNOS is False:
101 if os.path.isfile("/etc/product.conf") is True:
102 model_dict = {}
103 with open("/etc/product.conf") as f:
104 for line in f:
105 if "=" in line:
106 (key, val) = line.strip().split("=")
107 model_dict[key] = val
108
109 if "model" in model_dict and model_dict["model"] in [
110 "crpd",
111 "cbng",
112 "cmgd",
113 ]:
114 ON_JUNOS = True
115
116 auto_probe = 0 # default is no auto-probe
117
118 # ------------------------------------------------------------------------
119 # property: hostname
120 # ------------------------------------------------------------------------
121
122 @property
123 def hostname(self):
124 """
125 :returns: the host-name of the Junos device.
126 """
127 return (
128 self._hostname
129 if (self._hostname != "localhost")
130 else self.facts.get("hostname")
131 )
132
133 # ------------------------------------------------------------------------
134 # property: user
135 # ------------------------------------------------------------------------
136
137 @property
138 def user(self):
139 """
140 :returns: the login user (str) accessing the Junos device
141 """
142 return self._auth_user
143
144 # ------------------------------------------------------------------------
145 # property: password
146 # ------------------------------------------------------------------------
147
148 @property
149 def password(self):
150 """
151 :returns: ``None`` - do not provide the password
152 """
153 return None # read-only
154
155 @password.setter
156 def password(self, value):
157 """
158 Change the authentication password value. This is handy in case
159 the calling program needs to attempt different passwords.
160 """
161 self._auth_password = value
162
163 # ------------------------------------------------------------------------
164 # property: logfile
165 # ------------------------------------------------------------------------
166
167 @property
168 def logfile(self):
169 """
170 :returns: exsiting logfile ``file`` object.
171 """
172 return self._logfile
173
174 @logfile.setter
175 def logfile(self, value):
176 """
177 Assigns an opened file object to the device for logging
178 If there is an open logfile, and 'value' is ``None`` or ``False``
179 then close the existing file.
180
181 :param file value: An open ``file`` object.
182
183 :returns: the new logfile ``file`` object
184
185 :raises ValueError:
186 When **value** is not a ``file`` object
187 """
188 # got an existing file that we need to close
189 if (not value) and (self._logfile is not None):
190 rc = self._logfile.close()
191 self._logfile = False
192 return rc
193
194 if sys.version < "3":
195 if not isinstance(value, file):
196 raise ValueError("value must be a file object")
197 else:
198 import io
199
200 if not isinstance(value, io.TextIOWrapper):
201 raise ValueError("value must be a file object")
202
203 self._logfile = value
204 return self._logfile
205
206 # ------------------------------------------------------------------------
207 # property: timeout
208 # ------------------------------------------------------------------------
209
210 @property
211 def timeout(self):
212 """
213 :returns: the current RPC timeout value (int) in seconds.
214 """
215 return self._conn.timeout
216
217 @timeout.setter
218 def timeout(self, value):
219 """
220 Used to change the RPC timeout value (default=30 sec).
221
222 :param int value:
223 New timeout value in seconds
224 """
225 try:
226 self._conn.timeout = int(value)
227 except (ValueError, TypeError):
228 raise RuntimeError(
229 "could not convert timeout value of %s to an " "integer" % (value)
230 )
231
232 # ------------------------------------------------------------------------
233 # property: facts
234 # ------------------------------------------------------------------------
235
236 @property
237 def ofacts(self):
238 """
239 :returns: Device fact dictionary
240 """
241 if self._fact_style != "old" and self._fact_style != "both":
242 raise RuntimeError("Old-style facts gathering is not in use!")
243 if self._ofacts == {} and self.connected:
244 self.facts_refresh()
245 return self._ofacts
246
247 @ofacts.setter
248 def ofacts(self, value):
249 """read-only property"""
250 raise RuntimeError("facts is read-only!")
251
252 # ------------------------------------------------------------------------
253 # property: port
254 # ------------------------------------------------------------------------
255
256 @property
257 def port(self):
258 """
259 :returns: the port (str) to connect to the Junos device
260 """
261 return self._port
262
263 # ------------------------------------------------------------------------
264 # property: master
265 # ------------------------------------------------------------------------
266
267 @property
268 def master(self):
269 """
270 The mastership state of the current Routing Engine.
271
272 The current Routing Engine is the RE to which the NETCONF session is
273 connected.
274
275 .. note::
276 This property is based on new-style fact gathering and the
277 value of currently cached facts. If there is a chance the
278 mastership state may have changed since the facts were cached,
279 then dev.facts_refresh() should be invoked prior to checking
280 this property. If old-style fact gathering is in use,
281 this property will return None.
282
283 :returns: True if the current RE is the master Routing Engine. False if
284 the current RE is not the master Routing Engine. None if
285 unable to determine the state of the current Routing Engine.
286 """
287 master = None
288
289 # Make sure the 'current_re' fact has a value
290 if self.facts.get("current_re") is not None:
291 # Typical master case
292 if "master" in self.facts["current_re"]:
293 master = True
294 # Typical backup case
295 elif "backup" in self.facts["current_re"]:
296 master = False
297 # Some single chassis and single RE platforms don't have
298 # 'master' in the 'current_re' fact. It's best to check if it's a
299 # single chassis and single RE platform based on the
300 # 'RE_hw_mi' and '2RE' facts, not the 'current_re' fact.
301 elif (
302 self.facts.get("2RE") is False
303 and self.facts.get("RE_hw_mi") is False
304 and "re0" in self.facts["current_re"]
305 ):
306 master = True
307 # Is it an SRX cluster?
308 # If so, the cluster's "primary" is the "master"
309 elif self.facts.get("srx_cluster") is True:
310 if "primary" in self.facts["current_re"]:
311 master = True
312 else:
313 master = False
314 else:
315 # Might be a GNF case.
316 if (
317 self.re_name is not None
318 and "gnf" in self.re_name
319 and "-re" in self.re_name
320 ):
321 # Get the name of the GNF from re_name/
322 # re_name will be in the format gnfX-reY
323 (gnf, _) = self.re_name.split("-re", 1)
324 if gnf + "-master" in self.facts.get("current_re"):
325 master = True
326 elif gnf + "-backup" in self.facts.get("current_re"):
327 master = False
328 else:
329 # Might be a multi-chassis case where this RE is neither
330 # the master or the backup for the entire system. In that
331 # case, it's either a chassis master or a chassis backup.
332 for re_state in self.facts["current_re"]:
333 # Multi-chassis case. A chassis master/backup, but
334 # not the system master/backup.
335 if "-backup" in re_state or "-master" in re_state:
336 master = False
337 break
338 return master
339
340 @master.setter
341 def master(self, value):
342 """read-only property"""
343 raise RuntimeError("master is read-only!")
344
345 # ------------------------------------------------------------------------
346 # property: uptime
347 # ------------------------------------------------------------------------
348
349 @property
350 def uptime(self):
351 """
352 The uptime of the current Routing Engine.
353
354 The current Routing Engine is the RE to which the NETCONF session is
355 connected.
356
357 :returns: The number of seconds (int) since the current Routing Engine
358 was booted. If there is a problem gathering or parsing the
359 uptime information, None is returned.
360 :raises: May raise a specific jnpr.junos.RpcError or
361 jnpr.junos.ConnectError subclass if there is a problem
362 communicating with the device.
363 """
364 uptime = None
365 rsp = self.rpc.get_system_uptime_information(normalize=True)
366 if rsp is not None:
367 element = rsp.find(".//system-booted-time/time-length")
368 if element is not None:
369 uptime_string = element.get("seconds")
370 if uptime_string is not None:
371 uptime = int(uptime_string)
372 return uptime
373
374 @uptime.setter
375 def uptime(self, value):
376 """read-only property"""
377 raise RuntimeError("uptime is read-only!")
378
379 # ------------------------------------------------------------------------
380 # property: re_name
381 # ------------------------------------------------------------------------
382
383 @property
384 def re_name(self):
385 """
386 The name of the current Routing Engine.
387
388 The current Routing Engine is the RE to which the NETCONF session is
389 connected.
390
391 .. note::
392 This property is based on new-style fact gathering. If
393 old-style fact gathering is in use, this property will return None.
394
395 :returns: A string containing the name of the current Routing Engine or
396 None if unable to determine the state of the current
397 Routing Engine.
398 """
399 re_name = None
400
401 # Make sure the 'current_re' and 'hostname_info' facts have values
402 if (
403 self.facts.get("current_re") is not None
404 and self.facts.get("hostname_info") is not None
405 ):
406 # re_name should be the intersection of the values in the
407 # 'current_re' fact and the keys in the 'hostname_info' fact.
408 intersect = set(self.facts["current_re"]) & set(
409 self.facts["hostname_info"].keys()
410 )
411 # intersect should usually contain a single element (the RE's
412 # name) if things worked correctly.
413 if len(intersect) == 1:
414 re_name = list(intersect)[0]
415 # If intersect contains no elements
416 elif len(intersect) == 0:
417 # Look for the first value
418 # in 'current_re' which contains '-re'.
419 for re_state in self.facts["current_re"]:
420 if "-re" in re_state:
421 re_name = re_state
422 break
423 if re_name is None:
424 # Still haven't figured it out, if there's only one key
425 # in 'hostname_info', assume that.
426 all_re_names = list(self.facts["hostname_info"].keys())
427 if len(all_re_names) == 1:
428 re_name = all_re_names[0]
429 if re_name is None:
430 # Still haven't figured it out. Is this a bsys?
431 for re_state in self.facts["current_re"]:
432 match = re.search(r"^re\d+$", re_state)
433 if match:
434 re_string = "bsys-" + match.group(0)
435 if re_string in self.facts["hostname_info"].keys():
436 re_name = re_string
437 return re_name
438
439 @re_name.setter
440 def re_name(self, value):
441 """read-only property"""
442 raise RuntimeError("re_name is read-only!")
443
444 def _sshconf_lkup(self):
445 """Controls the ssh connection:
446 If using ssh_private_key_file on MacOS Mojave or greater
447 (specifically > OpenSSH_7.4p1) ensure that the keys are generated
448 in PEM format or convert existing 'new' keys to the PEM format:
449 Check format: `head -n1 ~/.ssh/some_key`
450 Correct RSA fomat: -----BEGIN RSA PRIVATE KEY-----
451 Incorrect OPENSSH format: -----BEGIN OPENSSH PRIVATE KEY-----
452 Convert an OPENSSH key to an RSA key: `ssh-keygen -p -m PEM -f ~/.ssh/some_key`
453 """
454 if self.__class__.__name__ == "Device" and self._sock_fd is not None:
455 return None
456 if self._ssh_config:
457 sshconf_path = os.path.expanduser(self._ssh_config)
458 else:
459 sshconf_path = os.path.join(os.path.expanduser("~"), ".ssh", "config")
460 if not os.path.exists(sshconf_path):
461 return None
462 else:
463 sshconf = paramiko.SSHConfig()
464 with open(sshconf_path, "r") as fp:
465 sshconf.parse(fp)
466 found = sshconf.lookup(self._hostname)
467 self._port = found.get("port", self._port)
468 self._conf_auth_user = found.get("user")
469 self._conf_ssh_private_key_file = found.get("identityfile")
470 return sshconf_path
471
472 def display_xml_rpc(self, command, format="xml"):
473 """
474 Executes the CLI command and returns the CLI xml object by default.
475
476 For example::
477 print dev.display_xml_rpc('show version').tag
478 or
479 print dev.display_xml_rpc('show version', format='text')
480
481 :param str command:
482 The CLI command to retrieve XML RPC for, e.g. "show version"
483
484 :param str format:
485 The return format, by default is XML. You can optionally select
486 "text" to return the XML structure as a string.
487 """
488 try:
489 command = command + "| display xml rpc"
490 rsp = self.rpc.cli(command, format="xml")
491 rsp = rsp.getparent().find(".//rpc")
492 if format == "text":
493 encode = None if sys.version < "3" else "unicode"
494 return etree.tostring(rsp[0], encoding=encode)
495 return rsp[0]
496 except TypeError:
497 return "No RPC equivalent found for: " + command
498 except:
499 return "invalid command: " + command
500
501 # ------------------------------------------------------------------------
502 # Template: retrieves a Jinja2 template
503 # ------------------------------------------------------------------------
504
505 def Template(self, filename, parent=None, gvars=None):
506 """
507 Used to return a Jinja2 :class:`Template`.
508
509 :param str filename:
510 file-path to Jinja2 template file on local device
511
512 :returns: Jinja2 :class:`Template` give **filename**.
513 """
514
515 return self._j2ldr.get_template(filename, parent, gvars)
516
517 # ------------------------------------------------------------------------
518 # property: manages
519 # ------------------------------------------------------------------------
520
521 @property
522 def manages(self):
523 """
524 :returns:
525 ``list`` of Resource Managers/Utilities attached to this
526 instance using the :meth:`bind` method.
527 """
528 return self._manages
529
530 # ------------------------------------------------------------------------
531 # dealing with bind aspects
532 # ------------------------------------------------------------------------
533
534 def bind(self, *vargs, **kvargs):
535 """
536 Used to attach things to this Device instance and make them a
537 property of the :class:Device instance. The most common use
538 for bind is attaching Utility instances to a :class:Device.
539 For example::
540
541 from jnpr.junos.utils.config import Config
542
543 dev.bind( cu=Config )
544 dev.cu.lock()
545 # ... load some changes
546 dev.cu.commit()
547 dev.cu.unlock()
548
549 :param list vargs:
550 A list of functions that will get bound as instance methods to
551 this Device instance.
552
553 .. warning:: Experimental.
554
555 :param new_property:
556 name/class pairs that will create resource-managers bound as
557 instance attributes to this Device instance. See code example above
558 """
559 if len(vargs):
560 for fn in vargs:
561 # check for name clashes before binding
562 if hasattr(self, fn.__name__):
563 raise ValueError(
564 "request attribute name %s already exists" % fn.__name__
565 )
566 for fn in vargs:
567 # bind as instance method, majik.
568 if sys.version < "3":
569 self.__dict__[fn.__name__] = types.MethodType(
570 fn, self, self.__class__
571 )
572 else:
573 self.__dict__[fn.__name__] = types.MethodType(fn, self.__class__)
574 return
575
576 # first verify that the names do not conflict with
577 # existing object attribute names
578
579 for name in kvargs.keys():
580 # check for name-clashes before binding
581 if hasattr(self, name):
582 raise ValueError("requested attribute name %s already exists" % name)
583
584 # now instantiate items and bind to this :Device:
585 for name, thing in kvargs.items():
586 new_inst = thing(self)
587 self.__dict__[name] = new_inst
588 self._manages.append(name)
589
590 @property
591 def _sshconf_path(self):
592 return self._sshconf_lkup()
593
594 # ------------------------------------------------------------------------
595 # probe
596 # ------------------------------------------------------------------------
597
598 def probe(self, timeout=5, intvtimeout=1):
599 """
600 Probe the device to determine if the Device can accept a remote
601 connection.
602 This method is meant to be called *prior* to :open():
603 This method will not work with ssh-jumphost environments.
604
605 :param int timeout:
606 The probe will report ``True``/``False`` if the device report
607 connectivity within this timeout (seconds)
608
609 :param int intvtimeout:
610 Timeout interval on the socket connection. Generally you should not
611 change this value, but you can if you want to twiddle the frequency
612 of the socket attempts on the connection
613
614 :returns: ``True`` if probe is successful, ``False`` otherwise
615 """
616 start = datetime.datetime.now()
617 end = start + datetime.timedelta(seconds=timeout)
618 probe_ok = True
619
620 while datetime.datetime.now() < end:
621 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
622 s.settimeout(intvtimeout)
623 try:
624 s.connect((self.hostname, int(self._port)))
625 s.shutdown(socket.SHUT_RDWR)
626 s.close()
627 break
628 except:
629 time.sleep(1)
630 pass
631 else:
632 probe_ok = False
633
634 return probe_ok
635
636 def cli_to_rpc_string(self, command):
637 """
638 Translate a CLI command string into the equivalent RPC method call.
639
640 Translates a CLI command string into a string which represents the
641 equivalent line of code using an RPC instead of a CLI command. Handles
642 RPCs with arguments.
643
644 .. note::
645 This method does NOT actually invoke the RPC equivalent.
646
647 :param str command:
648 The CLI command to translate, e.g. "show version"
649
650 :returns: (str) representing the RPC meta-method (including
651 attributes and arguments) which could be invoked instead of
652 cli(command). Returns None if there is no equivalent RPC for
653 command or if command is not a valid CLI command.
654 """
655
656 # Strip off any pipe modifiers
657 (command, _, _) = command.partition("|")
658 # Strip any leading or trailing whitespace
659 command = command.strip()
660 # Get the equivalent RPC
661 rpc = self.display_xml_rpc(command)
662 if isinstance(rpc, six.string_types):
663 # No RPC is available.
664 return None
665 rpc_string = "rpc.%s(" % (rpc.tag.replace("-", "_"))
666 arguments = []
667 for child in rpc:
668 key = child.tag.replace("-", "_")
669 if child.text:
670 value = "'" + child.text + "'"
671 else:
672 value = "True"
673 arguments.append("%s=%s" % (key, value))
674 if arguments:
675 rpc_string += ", ".join(arguments)
676 rpc_string += ")"
677 return rpc_string
678
679 # ------------------------------------------------------------------------
680 # cli - for cheating commands :-)
681 # ------------------------------------------------------------------------
682
683 def cli(self, command, format="text", warning=True):
684 """
685 Executes the CLI command and returns the CLI text output by default.
686
687 :param str command:
688 The CLI command to execute, e.g. "show version"
689
690 :param str format:
691 The return format, by default is text. You can optionally select
692 "xml" to return the XML structure.
693
694 .. note::
695 You can also use this method to obtain the XML RPC command for a
696 given CLI command by using the pipe filter ``| display xml rpc``.
697 When you do this, the return value is the XML RPC command. For
698 example if you provide as the command
699 ``show version | display xml rpc``, you will get back the XML
700 Element ``<get-software-information>``.
701
702 .. warning::
703 This function is provided for **DEBUG** purposes only!
704 **DO NOT** use this method for general automation purposes as
705 that puts you in the realm of "screen-scraping the CLI".
706 The purpose of the PyEZ framework is to migrate away from that
707 tooling pattern. Interaction with the device should be done via
708 the RPC function.
709
710 .. warning::
711 You cannot use "pipe" filters with **command** such as ``| match``
712 or ``| count``, etc. The only value use of the "pipe" is for the
713 ``| display xml rpc`` as noted above.
714 """
715 if "display xml rpc" not in command and warning is True:
716 # Get the equivalent rpc metamethod
717 rpc_string = self.cli_to_rpc_string(command)
718 if rpc_string is not None:
719 warning_string = "\nCLI command is for debug use only!\n"
720 warning_string += "Instead of:\ncli('%s')\n" % (command)
721 warning_string += "Use:\n%s\n" % (rpc_string)
722 warnings.simplefilter("always")
723 warnings.warn(warning_string, RuntimeWarning)
724 warnings.resetwarnings()
725
726 try:
727 rsp = self.rpc.cli(command=command, format=format)
728 if isinstance(rsp, dict) and format.lower() == "json":
729 return rsp
730 # rsp returned True means <rpc-reply> is empty, hence return
731 # empty str as would be the case on cli
732 # ex:
733 # <rpc-reply message-id="urn:uuid:281f624f-022b-11e6-bfa8">
734 # </rpc-reply>
735 if rsp is True:
736 return ""
737 if rsp.tag in ["output", "rpc-reply"]:
738 if rsp.tag == "output" and rsp.getparent() is not None:
739 rsp = rsp.getparent()
740 encode = None if sys.version < "3" else "unicode"
741 return etree.tostring(
742 rsp, method="text", with_tail=False, encoding=encode
743 )
744 if rsp.tag == "configuration-information":
745 return rsp.findtext("configuration-output")
746 if rsp.tag == "rpc":
747 return rsp[0]
748 return rsp
749 except (
750 EzErrors.ConnectClosedError,
751 EzErrors.RpcError,
752 EzErrors.RpcTimeoutError,
753 ) as ex:
754 raise ex
755 except Exception as ex:
756 warnings.warn(
757 "An unknown exception occurred : %s - please report." % ex,
758 RuntimeWarning,
759 )
760 raise ex
761
762 # ------------------------------------------------------------------------
763 # execute
764 # ------------------------------------------------------------------------
765
766 @normalizeDecorator
767 @timeoutDecorator
768 def execute(self, rpc_cmd, ignore_warning=False, **kvargs):
769 """
770 Executes an XML RPC and returns results as either XML or native python
771
772 :param rpc_cmd:
773 can either be an XML Element or xml-as-string. In either case
774 the command starts with the specific command element, i.e., not the
775 <rpc> element itself
776
777 :param ignore_warning: A boolean, string or list of string.
778 If the value is True, it will ignore all warnings regardless of the
779 warning message. If the value is a string, it will ignore
780 warning(s) if the message of each warning matches the string. If
781 the value is a list of strings, ignore warning(s) if the message of
782 each warning matches at least one of the strings in the list.
783
784 .. note::
785 When the value of ignore_warning is a string, or list of strings,
786 the string is actually used as a case-insensitive regular
787 expression pattern. If the string contains only alpha-numeric
788 characters, as shown in the above examples, this results in a
789 case-insensitive substring match. However, any regular expression
790 pattern supported by the re library may be used for more
791 complicated match conditions.
792
793 :param func to_py:
794 Is a caller provided function that takes the response and
795 will convert the results to native python types. all kvargs
796 will be passed to this function as well in the form::
797
798 to_py( self, rpc_rsp, **kvargs )
799
800 :raises ValueError:
801 When the **rpc_cmd** is of unknown origin
802
803 :raises PermissionError:
804 When the requested RPC command is not allowed due to
805 user-auth class privilege controls on Junos
806
807 :raises RpcError:
808 When an ``rpc-error`` element is contained in the RPC-reply and the
809 ``rpc-error`` element does not match the **ignore_warning** value.
810
811 :returns:
812 RPC-reply as XML object. If **to_py** is provided, then
813 that function is called, and return of that function is
814 provided back to the caller; presumably to convert the XML to
815 native python data-types (e.g. ``dict``).
816 """
817
818 if self.connected is not True:
819 raise EzErrors.ConnectClosedError(self)
820
821 if isinstance(rpc_cmd, str):
822 rpc_cmd_e = etree.XML(rpc_cmd)
823 elif isinstance(rpc_cmd, etree._Element):
824 rpc_cmd_e = rpc_cmd
825 else:
826 raise ValueError(
827 "Dont know what to do with rpc of type %s" % rpc_cmd.__class__.__name__
828 )
829
830 # invoking a bad RPC will cause a connection object exception
831 # will will be raised directly to the caller ... for now ...
832 # @@@ need to trap this and re-raise accordingly.
833
834 try:
835 rpc_rsp_e = self._rpc_reply(
836 rpc_cmd_e,
837 ignore_warning=ignore_warning,
838 filter_xml=kvargs.get("filter_xml"),
839 )
840 except NcOpErrors.TimeoutExpiredError:
841 # err is a TimeoutExpiredError from ncclient,
842 # which has no such attribute as xml.
843 raise EzErrors.RpcTimeoutError(self, rpc_cmd_e.tag, self.timeout)
844 except NcErrors.TransportError:
845 raise EzErrors.ConnectClosedError(self)
846 except RPCError as ex:
847 if hasattr(ex, "xml"):
848 rsp = JXML.remove_namespaces(ex.xml)
849 message = rsp.findtext("error-message")
850 # see if this is a permission error
851 if message and message == "permission denied":
852 raise EzErrors.PermissionError(cmd=rpc_cmd_e, rsp=rsp, errs=ex)
853 else:
854 rsp = None
855 raise EzErrors.RpcError(cmd=rpc_cmd_e, rsp=rsp, errs=ex)
856 # Something unexpected happened - raise it up
857 except Exception as err:
858 warnings.warn(
859 "An unknown exception occurred - please report.", RuntimeWarning
860 )
861 raise
862
863 # From 14.2 onward, junos supports JSON, so now code can be written as
864 # dev.rpc.get_route_engine_information({'format': 'json'})
865 # should not convert rpc response to json when loading json config
866 # as response should be rpc-reply xml object.
867
868 if rpc_cmd_e.tag != "load-configuration" and rpc_cmd_e.attrib.get("format") in [
869 "json",
870 "JSON",
871 ]:
872 ver_info = self.facts.get("version_info")
873 if ver_info and (
874 ver_info.major[0] >= 15
875 or (ver_info.major[0] == 14 and ver_info.major[1] >= 2)
876 ):
877 try:
878 return json.loads(rpc_rsp_e.text, strict=False)
879 except ValueError as ex:
880 # when data is {}{.*} types
881 if str(ex).startswith("Extra data"):
882 return json.loads(re.sub(r"\s?{\s?}\s?", "", rpc_rsp_e.text))
883 else:
884 raise JSONLoadError(ex, rpc_rsp_e.text)
885 else:
886 warnings.warn(
887 "Native JSON support is only from 14.2 onwards", RuntimeWarning
888 )
889
890 # This section is here for the possible use of something other than
891 # ncclient for RPCs that have embedded rpc-errors, need to check for
892 # those now.
893 # rpc_errs = rpc_rsp_e.xpath('.//rpc-error')
894 # if len(rpc_errs):
895 # raise EzErrors.RpcError(cmd=rpc_cmd_e, rsp=rpc_errs[0])
896
897 # skip the <rpc-reply> element and pass the caller first child element
898 # generally speaking this is what they really want. If they want to
899 # uplevel they can always call the getparent() method on it.
900
901 try:
902 ret_rpc_rsp = rpc_rsp_e[0]
903 except IndexError:
904 # For cases where reply are like
905 # <rpc-reply>
906 # protocol: operation-failed
907 # error: device asdf not found
908 # </rpc-reply>
909 if rpc_rsp_e.text is not None and rpc_rsp_e.text.strip() != "":
910 return rpc_rsp_e
911 # no children, so assume it means we are OK
912 return True
913
914 # if the caller provided a "to Python" conversion function, then invoke
915 # that now and return the results of that function. otherwise just
916 # return the RPC results as XML
917
918 if kvargs.get("to_py"):
919 return kvargs["to_py"](self, ret_rpc_rsp, **kvargs)
920 else:
921 return ret_rpc_rsp
922
923 # ------------------------------------------------------------------------
924 # facts
925 # ------------------------------------------------------------------------
926
927 def facts_refresh(
928 self, exception_on_failure=False, warnings_on_failure=None, keys=None
929 ):
930 """
931 Refresh the facts from the Junos device into :attr:`facts` property.
932 See :module:`jnpr.junos.facts` for a complete list of available facts.
933 For old-style facts, this causes all facts to be immediately reloaded.
934 For new-style facts, the current fact value(s) are deleted, and the
935 fact is reloaded on demand.
936
937 :param bool exception_on_failure: To raise exception when facts
938 gathering errors out. If True when new-style fact gathering is in
939 use, causes all facts to be reloaded rather than being loaded on
940 demand.
941 :param bool warnings_on_failure: To print a warning when fact gathering
942 errors out. The default for old-style facts gathering is
943 warnings_on_failure=True. The default for new-style facts gathering
944 is warnings_on_failure=False. If True when new-style fact gathering
945 is in use, causes all facts to be reloaded rather than being loaded
946 on demand.
947 :param str, set, list, or tuple keys: The set of keys in facts to
948 refresh. Note: Old-style facts gathering does not support
949 gathering individual facts, so this argument can only be
950 specified when new-style fact gathering is in use. In addition,
951 setting exception_on_failure or warnings_on_failure to True causes
952 all facts to be immediately refreshed, rather than being refreshed
953 on demand. For this reason, the keys argument can not be specified if
954 exception_on_failure or warnings_on_failure are True.
955
956 An example of specifying the keys argument as a string:
957 ```
958 dev.facts_refresh(keys='hostname')
959 ```
960
961 An example of specifying the keys argument as a tuple:
962 ```
963 dev.facts_refresh(keys=('hostname', 'hostname_info', 'domain', 'fqdn'))
964 ```
965 or as a list:
966 ```
967 dev.facts_refresh(keys=['hostname', 'hostname_info', 'domain', 'fqdn'])
968 ```
969 or as a set:
970 ```
971 dev.facts_refresh(keys={'hostname', 'hostname_info', 'domain', 'fqdn'})
972 ```
973
974 :raises RuntimeError:
975 If old-style fact gathering is in use and a keys argument is
976 specified.
977 """
978 if self._fact_style not in ["old", "new", "both"]:
979 raise RuntimeError("Unknown fact_style: %s" % (self._fact_style))
980 if self._fact_style == "old" or self._fact_style == "both":
981 if warnings_on_failure is None:
982 warnings_on_failure = True
983 if keys is not None:
984 raise RuntimeError(
985 "The keys argument can not be specified "
986 "when old-style fact gathering is in use!"
987 )
988 should_warn = False
989 for gather in FACT_LIST:
990 try:
991 gather(self, self._ofacts)
992 except:
993 if exception_on_failure:
994 raise
995 should_warn = True
996 if (
997 warnings_on_failure is True
998 and should_warn is True
999 and self._fact_style != "both"
1000 ):
1001 warnings.warn(
1002 "Facts gathering is incomplete. "
1003 "To know the reason call "
1004 '"dev.facts_refresh(exception_on_failure=True)"',
1005 RuntimeWarning,
1006 )
1007 if self._fact_style == "new" or self._fact_style == "both":
1008 if warnings_on_failure is None:
1009 warnings_on_failure = False
1010 self.facts._refresh(
1011 exception_on_failure=exception_on_failure,
1012 warnings_on_failure=warnings_on_failure,
1013 keys=keys,
1014 )
1015 return
1016
1017 # -----------------------------------------------------------------------
1018 # OVERLOADS
1019 # -----------------------------------------------------------------------
1020
1021 def __repr__(self):
1022 return "Device(%s)" % self.hostname
1023
1024
1025 class DeviceSessionListener(SessionListener):
1026 """
1027 Listens to Session class of Netconf Transport
1028 and detects errors in the transport.
1029 """
1030
1031 def __init__(self, device):
1032 self._device = device
1033
1034 def callback(self, root, raw):
1035 """Required by implementation but not used here."""
1036 pass
1037
1038 def errback(self, ex):
1039 """Called when an error occurs.
1040 Set the device's connected status to False.
1041 :type ex: :exc:`Exception`
1042 """
1043 self._device.connected = False
1044
1045
1046 class Device(_Connection):
1047 """
1048 Junos Device class.
1049
1050 :attr:`ON_JUNOS`:
1051 **READ-ONLY** -
1052 Auto-set to ``True`` when this code is running on a Junos device,
1053 vs. running on a local-server remotely connecting to a device.
1054
1055 :attr:`auto_probe`:
1056 When non-zero the call to :meth:`open` will probe for NETCONF
1057 reachability before proceeding with the NETCONF session establishment.
1058 If you want to enable this behavior by default, you could do the
1059 following in your code::
1060
1061 from jnpr.junos import Device
1062
1063 # set all device open to auto-probe with timeout of 10 sec
1064 Device.auto_probe = 10
1065
1066 dev = Device( ... )
1067 dev.open() # this will probe before attempting NETCONF connect
1068
1069 """
1070
1071 # -------------------------------------------------------------------------
1072 # PROPERTIES
1073 # -------------------------------------------------------------------------
1074
1075 # ------------------------------------------------------------------------
1076 # property: transform
1077 # ------------------------------------------------------------------------
1078
1079 @property
1080 def transform(self):
1081 """
1082 :returns: the current RPC XML Transformation.
1083 """
1084 try:
1085 return self._conn._device_handler.transform_reply
1086 except AttributeError:
1087 if self._conn is None:
1088 raise ConnectError(self, "Not connected to the Device")
1089
1090 @transform.setter
1091 def transform(self, func):
1092 """
1093 Used to change the RPC XML Transformation.
1094
1095 :param lambda value:
1096 New transform lambda
1097 """
1098 self._conn._device_handler.transform_reply = func
1099
1100 # -----------------------------------------------------------------------
1101 # CONSTRUCTOR
1102 # -----------------------------------------------------------------------
1103
1104 def __new__(cls, *args, **kwargs):
1105 if (
1106 kwargs.get("port") in [23, "23"]
1107 or kwargs.get("mode")
1108 or kwargs.get("cs_user") is not None
1109 ):
1110 from jnpr.junos.console import Console
1111
1112 if kwargs.get("conn_open_timeout", None):
1113 # Console already supports timeout while opening connections
1114 # via `timeout` parameter. Refer `Console` documentation
1115 # for more details.
1116
1117 # Note: The actual timeout may appear higher than set timeout as
1118 # the actual timeout is 3*(timeout+2)
1119 kwargs["timeout"] = kwargs.pop("conn_open_timeout")
1120
1121 instance = object.__new__(Console, *args, **kwargs)
1122 # Python only calls __init__() if the object returned from
1123 # __new__() is an instance of the class in which the __new__()
1124 # method is contained (here Device class). Hence calling __init__
1125 # explicitly.
1126 kwargs["host"] = args[0] if len(args) else kwargs.get("host")
1127 instance.__init__(**kwargs)
1128 return instance
1129 else:
1130 if sys.version < "3":
1131 return super(Device, cls).__new__(cls, *args, **kwargs)
1132 else:
1133 return super().__new__(cls)
1134
1135 def __init__(self, *vargs, **kvargs):
1136 """
1137 Device object constructor.
1138
1139 :param str vargs[0]: host-name or ipaddress. This is an
1140 alternative for **host**
1141
1142 :param str host:
1143 **REQUIRED** host-name or ipaddress of target device, unless sock_fd is provided
1144
1145 :param str sock_fd:
1146 **REQUIRED** file descriptor of an existing socket instead of providing a host.
1147 Used for outbound ssh.
1148
1149 :param str user:
1150 *OPTIONAL* login user-name, uses $USER if not provided
1151
1152 :param str passwd:
1153 *OPTIONAL* if not provided, assumed ssh-keys are enforced
1154
1155 :param int port:
1156 *OPTIONAL* NETCONF port (defaults to 830)
1157
1158 :param bool gather_facts:
1159 *OPTIONAL* For ssh mode default is ``True``. In case of console
1160 connection over telnet/serial it defaults to ``False``.
1161 If ``False`` and old-style fact gathering is in use then facts are
1162 not gathered on call to :meth:`open`. This argument is a no-op when
1163 new-style fact gathering is in use (the default.)
1164
1165 :param str fact_style:
1166 *OPTIONAL* The style of fact gathering to use. Valid values are:
1167 'new', 'old', or 'both'. The default is 'new'. The value 'both' is
1168 only present for debugging purposes. It will be removed in a future
1169 release. The value 'old' is only present to workaround bugs in
1170 new-style fact gathering. It will be removed in a future release.
1171
1172 :param str mode:
1173 *OPTIONAL* mode, mode for console connection (telnet/serial)
1174
1175 :param int baud:
1176 *OPTIONAL* baud, Used during serial console mode, default baud
1177 rate is 9600
1178
1179 :param int attempts:
1180 *OPTIONAL* attempts, for console connection. default is 10
1181
1182 :param bool auto_probe:
1183 *OPTIONAL* if non-zero then this enables auto_probe at time of
1184 :meth:`open` and defines the amount of time(sec) for the
1185 probe timeout
1186
1187 :param str ssh_private_key_file:
1188 *OPTIONAL* The path to the SSH private key file.
1189 This can be used if you need to provide a private key rather than
1190 loading the key into the ssh-key-ring/environment. if your
1191 ssh-key requires a password, then you must provide it via
1192 **passwd**
1193
1194 :param str ssh_config:
1195 *OPTIONAL* The path to the SSH configuration file.
1196 This can be used to load SSH information from a configuration file.
1197 By default ~/.ssh/config is queried.
1198
1199 :param bool normalize:
1200 *OPTIONAL* default is ``False``. If ``True`` then the
1201 XML returned by :meth:`execute` will have whitespace normalized
1202
1203 :param bool use_filter:
1204 *OPTIONAL* To choose between SAX and DOM parsing.
1205 default is ``False`` to use DOM.
1206 Select ``True`` to use SAX (if SAX input is provided).
1207
1208 :param int conn_open_timeout:
1209 *OPTIONAL* To specify the timeout in seconds, which will
1210 be used while opening SSH connection to the device
1211
1212 :param bool huge_tree:
1213 *OPTIONAL* parse XML with very deep trees and long text content.
1214 default is ``False``.
1215
1216 :param bool look_for_keys:
1217 *OPTIONAL* To disable public key authentication.
1218 default is ``None``.
1219
1220 :param str bind_addr:
1221 *OPTIONAL* To use (local) source IP address.
1222 default is ``None``.
1223
1224 :param bool hostkey_verify:
1225 *OPTIONAL* To enable ssh_known hostkey verify
1226 default is ``False``.
1227
1228 """
1229
1230 # ----------------------------------------
1231 # setup instance connection/open variables
1232 # ----------------------------------------
1233
1234 hostname = vargs[0] if len(vargs) else kvargs.get("host")
1235
1236 self._port = kvargs.get("port", 830)
1237 self._sock_fd = kvargs.get("sock_fd", None)
1238 self._gather_facts = kvargs.get("gather_facts", True)
1239 self._normalize = kvargs.get("normalize", False)
1240 self._auto_probe = kvargs.get("auto_probe", self.__class__.auto_probe)
1241 self._fact_style = kvargs.get("fact_style", "new")
1242 self._use_filter = kvargs.get("use_filter", False)
1243 self._huge_tree = kvargs.get("huge_tree", False)
1244 self._conn_open_timeout = kvargs.get("conn_open_timeout", 30)
1245 self._look_for_keys = kvargs.get("look_for_keys", None)
1246 self._bind_addr = kvargs.get("bind_addr", None)
1247 self._hostkey_verify = kvargs.get("hostkey_verify", False)
1248 if self._fact_style != "new":
1249 warnings.warn(
1250 "fact-style %s will be removed in a future "
1251 "release." % (self._fact_style),
1252 RuntimeWarning,
1253 )
1254
1255 if self.__class__.ON_JUNOS is True and hostname is None:
1256 # ---------------------------------
1257 # running on a Junos device locally
1258 # ---------------------------------
1259 self._auth_user = None
1260 self._auth_password = None
1261 self._hostname = "localhost"
1262 self._ssh_private_key_file = None
1263 self._ssh_config = None
1264 else:
1265 # --------------------------
1266 # making a remote connection
1267 # if hostname is None, this is an 'outbound-ssh' connection
1268 # which uses the established TCP connection from sock_fd
1269 # --------------------------
1270 if hostname is None and self._sock_fd is None:
1271 raise ValueError("You must provide either 'host' or 'sock_fd' value")
1272 self._hostname = hostname
1273 # user will default to $USER
1274 self._auth_user = os.getenv("USER")
1275 self._conf_auth_user = None
1276 self._conf_ssh_private_key_file = None
1277 # user can get updated by ssh_config
1278 self._ssh_config = kvargs.get("ssh_config")
1279 self._sshconf_lkup()
1280 # but if user or private key is explicit from call, then use it.
1281 self._auth_user = (
1282 kvargs.get("user") or self._conf_auth_user or self._auth_user
1283 )
1284 self._ssh_private_key_file = (
1285 kvargs.get("ssh_private_key_file") or self._conf_ssh_private_key_file
1286 )
1287 self._auth_password = kvargs.get("password") or kvargs.get("passwd")
1288
1289 # -----------------------------
1290 # initialize instance variables
1291 # ------------------------------
1292
1293 self._conn = None
1294 self._j2ldr = _Jinja2ldr
1295 self._manages = []
1296 self._ofacts = {}
1297
1298 # public attributes
1299 self.connected = False
1300 self.rpc = _RpcMetaExec(self)
1301 if self._fact_style == "old":
1302 self.facts = self.ofacts
1303 else:
1304 self.facts = _FactCache(self)
1305
1306 # -----------------------------------------------------------------------
1307 # Basic device methods
1308 # -----------------------------------------------------------------------
1309 @property
1310 def connected(self):
1311 return self._connected
1312
1313 @connected.setter
1314 def connected(self, value):
1315 if value in [True, False]:
1316 self._connected = value
1317
1318 def open(self, *vargs, **kvargs):
1319 """
1320 Opens a connection to the device using existing login/auth
1321 information.
1322
1323 :param bool gather_facts:
1324 If set to ``True``/``False`` will override the device
1325 instance value for only this open process
1326
1327 :param bool auto_probe:
1328 If non-zero then this enables auto_probe and defines the amount
1329 of time/seconds for the probe timeout
1330
1331 :param bool normalize:
1332 If set to ``True``/``False`` will override the device
1333 instance value for only this open process
1334
1335 :returns Device: Device instance (*self*).
1336
1337 :raises ProbeError:
1338 When **auto_probe** is ``True`` and the probe activity
1339 exceeds the timeout
1340
1341 :raises ConnectAuthError:
1342 When provided authentication credentials fail to login
1343
1344 :raises ConnectRefusedError:
1345 When the device does not have NETCONF enabled
1346
1347 :raises ConnectTimeoutError:
1348 When the the :meth:`Device.timeout` value is exceeded
1349 during the attempt to connect to the remote device
1350
1351 :raises ConnectError:
1352 When an error, other than the above, occurs. The
1353 originating ``Exception`` is assigned as ``err._orig``
1354 and re-raised to the caller.
1355 """
1356
1357 auto_probe = kvargs.get("auto_probe", self._auto_probe)
1358 if auto_probe != 0:
1359 if not self.probe(auto_probe):
1360 raise EzErrors.ProbeError(self)
1361
1362 try:
1363 ts_start = datetime.datetime.now()
1364
1365 # we want to enable the ssh-agent if-and-only-if we are
1366 # not given a password or an ssh key file.
1367 # in this condition it means we want to query the agent
1368 # for available ssh keys
1369
1370 allow_agent = bool(
1371 (self._auth_password is None) and (self._ssh_private_key_file is None)
1372 )
1373
1374 # option to disable ncclient transport ssh authentication
1375 # using public keys look_for_keys=False
1376 if self._look_for_keys is None:
1377 look_for_keys = True
1378 else:
1379 look_for_keys = self._look_for_keys
1380
1381 # option to enable ssh_known hosts key verification
1382 # using hostkey_verify=True
1383 # Default is disabled with hostkey_verify=False
1384 if self._hostkey_verify is None:
1385 hostkey_verify = False
1386 else:
1387 hostkey_verify = self._hostkey_verify
1388
1389 # open connection using ncclient transport
1390 self._conn = netconf_ssh.connect(
1391 host=self._hostname,
1392 port=self._port,
1393 sock_fd=self._sock_fd,
1394 username=self._auth_user,
1395 password=self._auth_password,
1396 hostkey_verify=hostkey_verify,
1397 key_filename=self._ssh_private_key_file,
1398 allow_agent=allow_agent,
1399 look_for_keys=look_for_keys,
1400 ssh_config=self._sshconf_lkup(),
1401 bind_addr=self._bind_addr,
1402 timeout=self._conn_open_timeout,
1403 device_params={
1404 "name": "junos",
1405 "local": self.__class__.ON_JUNOS,
1406 "use_filter": self._use_filter,
1407 },
1408 )
1409 self._conn._session.add_listener(DeviceSessionListener(self))
1410 except NcErrors.AuthenticationError as err:
1411 # bad authentication credentials
1412 raise EzErrors.ConnectAuthError(self)
1413
1414 except NcErrors.SSHError as err:
1415 # this is a bit of a hack for now, since we want to
1416 # know if the connection was refused or we simply could
1417 # not open a connection due to reachability. so using
1418 # a timestamp to differentiate the two conditions for now
1419 # if the diff is < 3 sec, then assume the host is
1420 # reachable, but NETCONF connection is refused.
1421
1422 ts_err = datetime.datetime.now()
1423 diff_ts = ts_err - ts_start
1424 if diff_ts.seconds < 3:
1425 raise EzErrors.ConnectRefusedError(self)
1426
1427 # at this point, we assume that the connection
1428 # has timed out due to ip-reachability issues
1429
1430 if str(err).find("not open") > 0:
1431 raise EzErrors.ConnectTimeoutError(self)
1432 else:
1433 # otherwise raise a generic connection
1434 # error for now. tag the new exception
1435 # with the original for debug
1436 cnx = EzErrors.ConnectError(self)
1437 cnx._orig = err
1438 raise cnx
1439
1440 except socket.gaierror:
1441 # invalid DNS name, so unreachable
1442 raise EzErrors.ConnectUnknownHostError(self)
1443
1444 except Exception as err:
1445 # anything else, we will re-raise as a
1446 # generic ConnectError
1447 cnx_err = EzErrors.ConnectError(self)
1448 cnx_err._orig = err
1449 raise cnx_err
1450
1451 if self._huge_tree:
1452 self._conn.huge_tree = True
1453 self.connected = True
1454
1455 self._nc_transform = self.transform
1456 self._norm_transform = lambda: JXML.normalize_xslt.encode("UTF-8")
1457
1458 # normalize argument to open() overrides normalize argument value
1459 # to __init__(). Save value to self._normalize where it is used by
1460 # normalizeDecorator()
1461 self._normalize = kvargs.get("normalize", self._normalize)
1462 if self._normalize is True:
1463 self.transform = self._norm_transform
1464
1465 gather_facts = kvargs.get("gather_facts", self._gather_facts)
1466 if gather_facts is True:
1467 self.facts_refresh()
1468
1469 return self
1470
1471 def close(self):
1472 """
1473 Closes the connection to the device only if connected.
1474 """
1475 if self.connected is True:
1476 self.connected = False
1477 try:
1478 self._conn.close_session()
1479 except NcOpErrors.TimeoutExpiredError:
1480 raise EzErrors.RpcTimeoutError(self, "close", self.timeout)
1481 except NcErrors.SessionCloseError:
1482 pass
1483
1484 @ignoreWarnDecorator
1485 def _rpc_reply(self, rpc_cmd_e, filter_xml=None):
1486 if NCCLIENT_FILTER_XML:
1487 return self._conn.rpc(rpc_cmd_e, filter_xml)._NCElement__doc
1488 else:
1489 return self._conn.rpc(rpc_cmd_e)._NCElement__doc
1490
1491 # -----------------------------------------------------------------------
1492 # Context Manager
1493 # -----------------------------------------------------------------------
1494
1495 def __enter__(self):
1496 self.open()
1497 return self
1498
1499 def __exit__(self, exc_type, exc_val, exc_tb):
1500 if self._conn.connected and not isinstance(exc_val, EzErrors.ConnectError):
1501 try:
1502 self.close()
1503 except Exception as ex:
1504 # exit should not raise any exception
1505 logger.error("Close in context manager hit exception: {}".format(ex))