Debian Codegraph @

lib/jnpr/junos/console.py

raw
1 import traceback
2 import sys
3 import logging
4 import warnings
5 import socket
6
7 # 3rd-party packages
8 from ncclient.devices.junos import JunosDeviceHandler
9 from lxml import etree
10 from jnpr.junos.transport.tty_telnet import Telnet
11 from jnpr.junos.transport.tty_serial import Serial
12 from jnpr.junos.transport.tty_ssh import SSH
13 from ncclient.xml_ import NCElement
14 from jnpr.junos.device import _Connection
15
16 # local modules
17 from jnpr.junos.rpcmeta import _RpcMetaExec
18 from jnpr.junos.factcache import _FactCache
19 from jnpr.junos import jxml as JXML
20 from jnpr.junos.ofacts import *
21 from jnpr.junos.decorators import ignoreWarnDecorator
22 from jnpr.junos.device import _Jinja2ldr
23
24 logger = logging.getLogger("jnpr.junos.console")
25
26
27 class Console(_Connection):
28 def __init__(self, **kvargs):
29 """
30 NoobDevice object constructor.
31
32 :param str host:
33 **REQUIRED** host-name or ipaddress of target device
34
35 :param str user:
36 *OPTIONAL* login user-name, uses root if not provided
37
38 :param str passwd:
39 *OPTIONAL* in console connection for device at zeroized state
40 password is not required
41
42 :param int port:
43 *OPTIONAL* port, defaults to '23' for telnet mode and
44 '/dev/ttyUSB0' for serial.
45
46 :param int baud:
47 *OPTIONAL* baud, default baud rate is 9600
48
49 :param str mode:
50 *OPTIONAL* mode, mode of connection (telnet/serial)
51 default is telnet
52
53 :param int timeout:
54 *OPTIONAL* timeout, default is 0.5
55
56 :param int attempts:
57 *OPTIONAL* attempts, default is 10
58
59 :param str ssh_config:
60 *OPTIONAL* The path to the SSH configuration file.
61 This can be used to load SSH information from a configuration file.
62 By default ~/.ssh/config is queried it will be used by SCP class.
63 So its assumed ssh is enabled by the time we use SCP functionality.
64
65 :param bool gather_facts:
66 *OPTIONAL* Defaults to ``False``. If ``False`` and old-style fact
67 gathering is in use then facts are not gathered on call to
68 :meth:`open`. This argument is a no-op when new-style fact
69 gathering is in use (the default.)
70
71 :param str fact_style:
72 *OPTIONAL* The style of fact gathering to use. Valid values are:
73 'new', 'old', or 'both'. The default is 'new'. The value 'both' is
74 only present for debugging purposes. It will be removed in a future
75 release. The value 'old' is only present to workaround bugs in
76 new-style fact gathering. It will be removed in a future release.
77
78 :param bool console_has_banner:
79 *OPTIONAL* default is ``False``. If ``False`` then in case of a
80 hung state, <close-session/> rpc is sent to the console.
81 If ``True``, after sleep(5), a new-line is sent
82
83 """
84
85 # ----------------------------------------
86 # setup instance connection/open variables
87 # ----------------------------------------
88
89 self._tty = None
90 self._ofacts = {}
91 self.connected = False
92 self._skip_logout = False
93 self.results = dict(changed=False, failed=False, errmsg=None)
94
95 # hostname is not required in serial mode connection
96 self._hostname = kvargs.get("host")
97 self._auth_user = kvargs.get("user", "root")
98 self._conf_auth_user = None
99 self._conf_ssh_private_key_file = None
100 self._auth_password = kvargs.get("password", "") or kvargs.get("passwd", "")
101 self.cs_user = kvargs.get("cs_user")
102 self.cs_passwd = kvargs.get("cs_passwd")
103 self._port = kvargs.get("port", "22" if self.cs_user else "23")
104 self._mode = kvargs.get("mode", None if self.cs_user else "telnet")
105 self._baud = kvargs.get("baud", "9600")
106 if self._hostname:
107 self._ssh_config = kvargs.get("ssh_config")
108 self._sshconf_lkup()
109 self._ssh_private_key_file = (
110 kvargs.get("ssh_private_key_file") or self._conf_ssh_private_key_file
111 )
112 self._timeout = kvargs.get("timeout", "0.5")
113 self._normalize = kvargs.get("normalize", False)
114 self._attempts = kvargs.get("attempts", 10)
115 self._gather_facts = kvargs.get("gather_facts", False)
116 self._fact_style = kvargs.get("fact_style", "new")
117 self._use_filter = False
118 self._huge_tree = kvargs.get("huge_tree", False)
119 if self._fact_style != "new":
120 warnings.warn(
121 "fact-style %s will be removed in "
122 "a future release." % (self._fact_style),
123 RuntimeWarning,
124 )
125 self.console_has_banner = kvargs.get("console_has_banner", False)
126 self.rpc = _RpcMetaExec(self)
127 self._manages = []
128 self.junos_dev_handler = JunosDeviceHandler(
129 device_params={"name": "junos", "local": False}
130 )
131 self._conn = None
132 self._j2ldr = _Jinja2ldr
133 if self._fact_style == "old":
134 self.facts = self.ofacts
135 else:
136 self.facts = _FactCache(self)
137
138 @property
139 def timeout(self):
140 """
141 :returns: current console connection timeout value (int) in seconds.
142 """
143 return self._timeout
144
145 @timeout.setter
146 def timeout(self, value):
147 """
148 Used to change the console connection timeout value (default=0.5 sec).
149
150 :param int value:
151 New timeout value in seconds
152 """
153 self._timeout = value
154
155 @property
156 def transform(self):
157 """
158 :returns: the current RPC XML Transformation.
159 """
160 return self.junos_dev_handler.transform_reply
161
162 @transform.setter
163 def transform(self, func):
164 """
165 Used to change the RPC XML Transformation.
166
167 :param lambda value:
168 New transform lambda
169 """
170 self.junos_dev_handler.transform_reply = func
171
172 def open(self, *vargs, **kvargs):
173 """
174 Opens a connection to the device using existing login/auth
175 information.
176
177 :param bool gather_facts:
178 If set to ``True``/``False`` will override the device
179 instance value for only this open process
180 """
181
182 # ---------------------------------------------------------------
183 # validate device hostname or IP address
184 # ---------------------------------------------------------------
185 if (
186 (self._mode and self._mode.upper() == "TELNET") or self.cs_user is not None
187 ) and self._hostname is None:
188 self.results["failed"] = True
189 self.results["errmsg"] = "ERROR: Device hostname/IP not specified !!!"
190 return self.results
191
192 # ---------------------------------------------------------------
193 # validate console server and password. Password-less connection
194 # is not supported
195 # ---------------------------------------------------------------
196 if self.cs_user is not None and self.cs_passwd is None:
197 self.results["failed"] = True
198 self.results["errmsg"] = (
199 "ERROR: Console SSH, Password-less connection is " "not supported !!!"
200 )
201 logger.error(self.results["errmsg"])
202 return self.results
203
204 # --------------------
205 # login to the CONSOLE
206 # --------------------
207 try:
208 self._tty_login()
209 except RuntimeError as err:
210 logger.error("ERROR: {}:{}\n".format("login", str(err)))
211 logger.error(
212 "\nComplete traceback message: {}".format(traceback.format_exc())
213 )
214 raise err
215 except Exception as ex:
216 logger.error("Exception occurred: {}:{}\n".format("login", str(ex)))
217 raise ex
218 self.connected = True
219
220 self._nc_transform = self.transform
221 self._norm_transform = lambda: JXML.normalize_xslt.encode("UTF-8")
222
223 # normalize argument to open() overrides normalize argument value
224 # to __init__(). Save value to self._normalize where it is used by
225 # normalizeDecorator()
226 self._normalize = kvargs.get("normalize", self._normalize)
227 if self._normalize is True:
228 self.transform = self._norm_transform
229
230 gather_facts = kvargs.get("gather_facts", self._gather_facts)
231 if gather_facts is True:
232 logger.info("facts: retrieving device facts...")
233 self.facts_refresh()
234 self.results["facts"] = self.facts
235 self._conn = self._tty
236 return self
237
238 def close(self, skip_logout=False):
239 """
240 Closes the connection to the device.
241 """
242 if skip_logout is False and self.connected is True:
243 try:
244 self._tty_logout()
245 except socket.error as err:
246 # if err contains "Connection reset by peer" connection to the
247 # device got closed
248 if "Connection reset by peer" not in str(err):
249 raise err
250 except EOFError as err:
251 if "telnet connection closed" not in str(err):
252 raise err
253 except Exception as err:
254 logger.error("ERROR {}:{}\n".format("logout", str(err)))
255 raise err
256 self.connected = False
257 elif self.connected is True:
258 try:
259 self._tty._tty_close()
260 except Exception as err:
261 logger.error("ERROR {}:{}\n".format("close", str(err)))
262 logger.error(
263 "\nComplete traceback message: {}".format(traceback.format_exc())
264 )
265 raise err
266 self.connected = False
267
268 @ignoreWarnDecorator
269 def _rpc_reply(self, rpc_cmd_e, *args, **kwargs):
270 encode = None if sys.version < "3" else "unicode"
271 rpc_cmd = (
272 etree.tostring(rpc_cmd_e, encoding=encode)
273 if isinstance(rpc_cmd_e, etree._Element)
274 else rpc_cmd_e
275 )
276 reply = self._tty.nc.rpc(rpc_cmd)
277 rpc_rsp_e = NCElement(
278 reply, self.junos_dev_handler.transform_reply(), self._huge_tree
279 )._NCElement__doc
280 return rpc_rsp_e
281
282 # -------------------------------------------------------------------------
283 # LOGIN/LOGOUT
284 # -------------------------------------------------------------------------
285
286 def _tty_login(self):
287 tty_args = dict()
288 tty_args["user"] = self._auth_user
289 tty_args["passwd"] = self._auth_password
290 tty_args["timeout"] = float(self._timeout)
291 tty_args["attempts"] = int(self._attempts)
292 tty_args["baud"] = self._baud
293 tty_args["huge_tree"] = self._huge_tree
294 if self._mode and self._mode.upper() == "TELNET":
295 tty_args["host"] = self._hostname
296 tty_args["port"] = self._port
297 tty_args["console_has_banner"] = self.console_has_banner
298 self.console = ("telnet", self._hostname, self.port)
299 self._tty = Telnet(**tty_args)
300 elif self.cs_user is not None:
301 tty_args["cs_user"] = self.cs_user
302 tty_args["cs_passwd"] = self.cs_passwd
303 tty_args["host"] = self._hostname
304 tty_args["port"] = self._port
305 tty_args["console_has_banner"] = self.console_has_banner
306 tty_args["ssh_private_key_file"] = self._ssh_private_key_file
307 self.console = ("ssh", self._hostname, self.port)
308 self._tty = SSH(**tty_args)
309 elif self._mode.upper() == "SERIAL":
310 tty_args["port"] = self._port
311 self.console = ("serial", self._port)
312 self._tty = Serial(**tty_args)
313 else:
314 logger.error("Mode should be either telnet or serial")
315 raise AttributeError("Mode to be telnet/serial")
316
317 self._tty.login()
318
319 def _tty_logout(self):
320 self._tty.logout()
321
322 def zeroize(self):
323 """perform device ZEROIZE actions"""
324 logger.info("zeroize : ZEROIZE device, rebooting")
325 self._tty.nc.zeroize()
326 self._skip_logout = True
327 self.results["changed"] = True
328
329 # -----------------------------------------------------------------------
330 # Context Manager
331 # -----------------------------------------------------------------------
332
333 def __enter__(self):
334 self.open()
335 return self
336
337 def __exit__(self, exc_type, exc_val, exc_tb):
338 if self.connected:
339 self.close()