robotframework-telnetlibrary 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
TelnetLibrary.py ADDED
@@ -0,0 +1,1237 @@
1
+ # Copyright 2008-2015 Nokia Networks
2
+ # Copyright 2016- Robot Framework Foundation
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from contextlib import contextmanager
17
+ import inspect
18
+ import re
19
+ import pyte
20
+ import socket
21
+ import struct
22
+ import telnetlib
23
+ import time
24
+
25
+ from robot.api import logger
26
+ from robot.api.deco import keyword
27
+ from robot.utils import (ConnectionCache, is_bytes, is_string, is_truthy,
28
+ secs_to_timestr, seq2str, timestr_to_secs)
29
+
30
+
31
+ class TelnetLibrary:
32
+ """A library providing communication over Telnet connections.
33
+
34
+ ``TelnetLibrary`` is Robot Framework's library that makes it possible to
35
+ connect to Telnet servers and execute commands on the opened connections.
36
+
37
+ == Table of contents ==
38
+
39
+ %TOC%
40
+
41
+ = Connections =
42
+
43
+ The first step of using ``TelnetLibrary`` is opening a connection with `Open
44
+ Connection` keyword. Typically the next step is logging in with `Login`
45
+ keyword, and in the end the opened connection can be closed with `Close
46
+ Connection`.
47
+
48
+ It is possible to open multiple connections and switch the active one
49
+ using `Switch Connection`. `Close All Connections` can be used to close
50
+ all the connections, which is especially useful in suite teardowns to
51
+ guarantee that all connections are always closed.
52
+
53
+ = Writing and reading =
54
+
55
+ After opening a connection and possibly logging in, commands can be
56
+ executed or text written to the connection for other reasons using `Write`
57
+ and `Write Bare` keywords. The main difference between these two is that
58
+ the former adds a [#Configuration|configurable newline] after the text
59
+ automatically.
60
+
61
+ After writing something to the connection, the resulting output can be
62
+ read using `Read`, `Read Until`, `Read Until Regexp`, and `Read Until
63
+ Prompt` keywords. Which one to use depends on the context, but the latest
64
+ one is often the most convenient.
65
+
66
+ As a convenience when running a command, it is possible to use `Execute
67
+ Command` that simply uses `Write` and `Read Until Prompt` internally.
68
+ `Write Until Expected Output` is useful if you need to wait until writing
69
+ something produces a desired output.
70
+
71
+ Written and read text is automatically encoded/decoded using a
72
+ [#Configuration|configured encoding].
73
+
74
+ The ANSI escape codes, like cursor movement and color codes, are
75
+ normally returned as part of the read operation. If an escape code occurs
76
+ in middle of a search pattern it may also prevent finding the searched
77
+ string. `Terminal emulation` can be used to process these
78
+ escape codes as they would be if a real terminal would be in use.
79
+
80
+ = Configuration =
81
+
82
+ Many aspects related the connections can be easily configured either
83
+ globally or per connection basis. Global configuration is done when
84
+ [#Importing|library is imported], and these values can be overridden per
85
+ connection by `Open Connection` or with setting specific keywords
86
+ `Set Timeout`, `Set Newline`, `Set Prompt`, `Set Encoding`,
87
+ `Set Default Log Level` and `Set Telnetlib Log Level`.
88
+
89
+ Values of ``environ_user``, ``window_size``, ``terminal_emulation``, and
90
+ ``terminal_type`` can not be changed after opening the connection.
91
+
92
+ == Timeout ==
93
+
94
+ Timeout defines how long is the maximum time to wait when reading
95
+ output. It is used internally by `Read Until`, `Read Until Regexp`,
96
+ `Read Until Prompt`, and `Login` keywords. The default value is 3 seconds.
97
+
98
+ == Connection Timeout ==
99
+
100
+ Connection Timeout defines how long is the maximum time to wait when
101
+ opening the telnet connection. It is used internally by `Open Connection`.
102
+ The default value is the system global default timeout.
103
+
104
+ == Newline ==
105
+
106
+ Newline defines which line separator `Write` keyword should use. The
107
+ default value is ``CRLF`` that is typically used by Telnet connections.
108
+
109
+ Newline can be given either in escaped format using ``\\n`` and ``\\r`` or
110
+ with special ``LF`` and ``CR`` syntax.
111
+
112
+ Examples:
113
+ | `Set Newline` | \\n |
114
+ | `Set Newline` | CRLF |
115
+
116
+ == Prompt ==
117
+
118
+ Often the easiest way to read the output of a command is reading all
119
+ the output until the next prompt with `Read Until Prompt`. It also makes
120
+ it easier, and faster, to verify did `Login` succeed.
121
+
122
+ Prompt can be specified either as a normal string or a regular expression.
123
+ The latter is especially useful if the prompt changes as a result of
124
+ the executed commands. Prompt can be set to be a regular expression
125
+ by giving ``prompt_is_regexp`` argument a true value (see `Boolean
126
+ arguments`).
127
+
128
+ Examples:
129
+ | `Open Connection` | lolcathost | prompt=$ |
130
+ | `Set Prompt` | (> |# ) | prompt_is_regexp=true |
131
+
132
+ == Encoding ==
133
+
134
+ To ease handling text containing non-ASCII characters, all written text is
135
+ encoded and read text decoded by default. The default encoding is UTF-8
136
+ that works also with ASCII. Encoding can be disabled by using a special
137
+ encoding value ``NONE``. This is mainly useful if you need to get the bytes
138
+ received from the connection as-is.
139
+
140
+ Notice that when writing to the connection, only Unicode strings are
141
+ encoded using the defined encoding. Byte strings are expected to be already
142
+ encoded correctly. Notice also that normal text in data is passed to
143
+ the library as Unicode and you need to use variables to use bytes.
144
+
145
+ It is also possible to configure the error handler to use if encoding or
146
+ decoding characters fails. Accepted values are the same that encode/decode
147
+ functions in Python strings accept. In practice the following values are
148
+ the most useful:
149
+
150
+ - ``ignore``: ignore characters that cannot be encoded (default)
151
+ - ``strict``: fail if characters cannot be encoded
152
+ - ``replace``: replace characters that cannot be encoded with a replacement
153
+ character
154
+
155
+ Examples:
156
+ | `Open Connection` | lolcathost | encoding=Latin1 | encoding_errors=strict |
157
+ | `Set Encoding` | ISO-8859-15 |
158
+ | `Set Encoding` | errors=ignore |
159
+
160
+ == Default log level ==
161
+
162
+ Default log level specifies the log level keywords use for `logging` unless
163
+ they are given an explicit log level. The default value is ``INFO``, and
164
+ changing it, for example, to ``DEBUG`` can be a good idea if there is lot
165
+ of unnecessary output that makes log files big.
166
+
167
+ == Terminal type ==
168
+
169
+ By default the TelnetLibrary does not negotiate any specific terminal type
170
+ with the server. If a specific terminal type, for example ``vt100``, is
171
+ desired, the terminal type can be configured in `importing` and with
172
+ `Open Connection`.
173
+
174
+ == Window size ==
175
+
176
+ Window size for negotiation with the server can be configured when
177
+ `importing` the library and with `Open Connection`.
178
+
179
+ == USER environment variable ==
180
+
181
+ Telnet protocol allows the ``USER`` environment variable to be sent when
182
+ connecting to the server. On some servers it may happen that there is no
183
+ login prompt, and on those cases this configuration option will allow still
184
+ to define the desired username. The option ``environ_user`` can be used in
185
+ `importing` and with `Open Connection`.
186
+
187
+ = Terminal emulation =
188
+
189
+ TelnetLibrary supports terminal
190
+ emulation with [http://pyte.readthedocs.io|Pyte]. Terminal emulation
191
+ will process the output in a virtual screen. This means that ANSI escape
192
+ codes, like cursor movements, and also control characters, like
193
+ carriage returns and backspaces, have the same effect on the result as they
194
+ would have on a normal terminal screen. For example the sequence
195
+ ``acdc\\x1b[3Dbba`` will result in output ``abba``.
196
+
197
+ Terminal emulation is taken into use by giving ``terminal_emulation``
198
+ argument a true value (see `Boolean arguments`) either in the library
199
+ initialization or with `Open Connection`.
200
+
201
+ As Pyte approximates vt-style terminal, you may also want to set the
202
+ terminal type as ``vt100``. We also recommend that you increase the window
203
+ size, as the terminal emulation will break all lines that are longer than
204
+ the window row length.
205
+
206
+ When terminal emulation is used, the `newline` and `encoding` can not be
207
+ changed anymore after opening the connection.
208
+
209
+ Examples:
210
+ | `Open Connection` | localhost | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 |
211
+
212
+ Due to backwards incompatible changes in Pyte, versions of Pyte older than
213
+ 0.6 are not supported. Latest Pyte version can be installed (or upgraded)
214
+ with ``pip install --upgrade pyte``.
215
+
216
+ = Logging =
217
+
218
+ All keywords that read something log the output. These keywords take the
219
+ log level to use as an optional argument, and if no log level is specified
220
+ they use the [#Configuration|configured] default value.
221
+
222
+ The valid log levels to use are ``TRACE``, ``DEBUG``, ``INFO`` (default),
223
+ and ``WARN``. Levels below ``INFO`` are not shown in log files by default
224
+ whereas warnings are shown more prominently.
225
+
226
+ The [http://docs.python.org/library/telnetlib.html|telnetlib module]
227
+ used by this library has a custom logging system for logging content it
228
+ sends and receives. By default these messages are written using ``TRACE``
229
+ level, but the level is configurable with the ``telnetlib_log_level``
230
+ option either in the library initialization, to the `Open Connection`
231
+ or by using the `Set Telnetlib Log Level` keyword to the active
232
+ connection. Special level ``NONE`` con be used to disable the logging
233
+ altogether.
234
+
235
+ = Time string format =
236
+
237
+ Timeouts and other times used must be given as a time string using format
238
+ like ``15 seconds`` or ``1min 10s``. If the timeout is given as just
239
+ a number, for example, ``10`` or ``1.5``, it is considered to be seconds.
240
+ The time string format is described in more detail in an appendix of
241
+ [http://robotframework.org/robotframework/#user-guide|Robot Framework User Guide].
242
+
243
+ = Boolean arguments =
244
+
245
+ Some keywords accept arguments that are handled as Boolean values true or
246
+ false. If such an argument is given as a string, it is considered false if
247
+ it is an empty string or equal to ``FALSE``, ``NONE``, ``NO``, ``OFF`` or
248
+ ``0``, case-insensitively. Other strings are considered true regardless
249
+ their value, and other argument types are tested using the same
250
+ [http://docs.python.org/library/stdtypes.html#truth|rules as in Python].
251
+
252
+ True examples:
253
+ | `Open Connection` | lolcathost | terminal_emulation=True | # Strings are generally true. |
254
+ | `Open Connection` | lolcathost | terminal_emulation=yes | # Same as the above. |
255
+ | `Open Connection` | lolcathost | terminal_emulation=${TRUE} | # Python ``True`` is true. |
256
+ | `Open Connection` | lolcathost | terminal_emulation=${42} | # Numbers other than 0 are true. |
257
+
258
+ False examples:
259
+ | `Open Connection` | lolcathost | terminal_emulation=False | # String ``false`` is false. |
260
+ | `Open Connection` | lolcathost | terminal_emulation=no | # Also string ``no`` is false. |
261
+ | `Open Connection` | lolcathost | terminal_emulation=${EMPTY} | # Empty string is false. |
262
+ | `Open Connection` | lolcathost | terminal_emulation=${FALSE} | # Python ``False`` is false. |
263
+
264
+ Considering string ``NONE`` false is new in Robot Framework 3.0.3 and
265
+ considering also ``OFF`` and ``0`` false is new in Robot Framework 3.1.
266
+ """
267
+ ROBOT_LIBRARY_SCOPE = 'SUITE'
268
+ ROBOT_LIBRARY_VERSION = '1.0.0'
269
+
270
+ def __init__(self, timeout='3 seconds', newline='CRLF',
271
+ prompt=None, prompt_is_regexp=False,
272
+ encoding='UTF-8', encoding_errors='ignore',
273
+ default_log_level='INFO', window_size=None,
274
+ environ_user=None, terminal_emulation=False,
275
+ terminal_type=None, telnetlib_log_level='TRACE',
276
+ connection_timeout=None):
277
+ """TelnetLibrary can be imported with optional configuration parameters.
278
+
279
+ Configuration parameters are used as default values when new
280
+ connections are opened with `Open Connection` keyword. They can also be
281
+ overridden after opening the connection using the `Set ...` `keywords`.
282
+ See these keywords as well as `Configuration`, `Terminal emulation` and
283
+ `Logging` sections above for more information about these parameters
284
+ and their possible values.
285
+
286
+ See `Time string format` and `Boolean arguments` sections for
287
+ information about using arguments accepting times and Boolean values,
288
+ respectively.
289
+
290
+ Examples (use only one of these):
291
+ | = Setting = | = Value = | = Value = | = Value = | = Value = | = Comment = |
292
+ | Library | TelnetLibrary | | | | # default values |
293
+ | Library | TelnetLibrary | 5 seconds | | | # set only timeout |
294
+ | Library | TelnetLibrary | newline=LF | encoding=ISO-8859-1 | | # set newline and encoding using named arguments |
295
+ | Library | TelnetLibrary | prompt=$ | | | # set prompt |
296
+ | Library | TelnetLibrary | prompt=(> |# ) | prompt_is_regexp=yes | | # set prompt as a regular expression |
297
+ | Library | TelnetLibrary | terminal_emulation=True | terminal_type=vt100 | window_size=400x100 | # use terminal emulation with defined window size and terminal type |
298
+ | Library | TelnetLibrary | telnetlib_log_level=NONE | | | # disable logging messages from the underlying telnetlib |
299
+ """
300
+ self._timeout = timeout or 3.0
301
+ self._set_connection_timeout(connection_timeout)
302
+ self._newline = newline or 'CRLF'
303
+ self._prompt = (prompt, prompt_is_regexp)
304
+ self._encoding = encoding
305
+ self._encoding_errors = encoding_errors
306
+ self._default_log_level = default_log_level
307
+ self._window_size = window_size
308
+ self._environ_user = environ_user
309
+ self._terminal_emulation = terminal_emulation
310
+ self._terminal_type = terminal_type
311
+ self._telnetlib_log_level = telnetlib_log_level
312
+ self._cache = ConnectionCache()
313
+ self._conn = None
314
+ self._conn_kws = self._lib_kws = None
315
+
316
+ def get_keyword_names(self):
317
+ return self._get_library_keywords() + self._get_connection_keywords()
318
+
319
+ def _get_library_keywords(self):
320
+ if self._lib_kws is None:
321
+ self._lib_kws = self._get_keywords(self, ['get_keyword_names'])
322
+ return self._lib_kws
323
+
324
+ def _get_keywords(self, source, excluded):
325
+ return [name for name in dir(source)
326
+ if self._is_keyword(name, source, excluded)]
327
+
328
+ def _is_keyword(self, name, source, excluded):
329
+ return (name not in excluded and
330
+ not name.startswith('_') and
331
+ name != 'get_keyword_names' and
332
+ inspect.ismethod(getattr(source, name)))
333
+
334
+ def _get_connection_keywords(self):
335
+ if self._conn_kws is None:
336
+ conn = self._get_connection()
337
+ excluded = [name for name in dir(telnetlib.Telnet())
338
+ if name not in ['write', 'read', 'read_until']]
339
+ self._conn_kws = self._get_keywords(conn, excluded)
340
+ return self._conn_kws
341
+
342
+ def __getattr__(self, name):
343
+ if name not in self._get_connection_keywords():
344
+ raise AttributeError(name)
345
+ # If no connection is initialized, get attributes from a non-active
346
+ # connection. This makes it possible for Robot to create keyword
347
+ # handlers when it imports the library.
348
+ return getattr(self._conn or self._get_connection(), name)
349
+
350
+ @keyword(types=None)
351
+ def open_connection(self, host, alias=None, port=23, timeout=None,
352
+ newline=None, prompt=None, prompt_is_regexp=False,
353
+ encoding=None, encoding_errors=None,
354
+ default_log_level=None, window_size=None,
355
+ environ_user=None, terminal_emulation=None,
356
+ terminal_type=None, telnetlib_log_level=None,
357
+ connection_timeout=None):
358
+ """Opens a new Telnet connection to the given host and port.
359
+
360
+ The ``timeout``, ``newline``, ``prompt``, ``prompt_is_regexp``,
361
+ ``encoding``, ``default_log_level``, ``window_size``, ``environ_user``,
362
+ ``terminal_emulation``, ``terminal_type`` and ``telnetlib_log_level``
363
+ arguments get default values when the library is [#Importing|imported].
364
+ Setting them here overrides those values for the opened connection.
365
+ See `Configuration`, `Terminal emulation` and `Logging` sections for
366
+ more information about these parameters and their possible values.
367
+
368
+ Possible already opened connections are cached and it is possible to
369
+ switch back to them using `Switch Connection` keyword. It is possible to
370
+ switch either using explicitly given ``alias`` or using index returned
371
+ by this keyword. Indexing starts from 1 and is reset back to it by
372
+ `Close All Connections` keyword.
373
+ """
374
+ timeout = timeout or self._timeout
375
+ connection_timeout = (timestr_to_secs(connection_timeout)
376
+ if connection_timeout
377
+ else self._connection_timeout)
378
+ newline = newline or self._newline
379
+ encoding = encoding or self._encoding
380
+ encoding_errors = encoding_errors or self._encoding_errors
381
+ default_log_level = default_log_level or self._default_log_level
382
+ window_size = self._parse_window_size(window_size or self._window_size)
383
+ environ_user = environ_user or self._environ_user
384
+ if terminal_emulation is None:
385
+ terminal_emulation = self._terminal_emulation
386
+ terminal_type = terminal_type or self._terminal_type
387
+ telnetlib_log_level = telnetlib_log_level or self._telnetlib_log_level
388
+ if not prompt:
389
+ prompt, prompt_is_regexp = self._prompt
390
+ logger.info('Opening connection to %s:%s with prompt: %s%s'
391
+ % (host, port, prompt, ' (regexp)' if prompt_is_regexp else ''))
392
+ self._conn = self._get_connection(host, port, timeout, newline,
393
+ prompt, is_truthy(prompt_is_regexp),
394
+ encoding, encoding_errors,
395
+ default_log_level,
396
+ window_size,
397
+ environ_user,
398
+ is_truthy(terminal_emulation),
399
+ terminal_type,
400
+ telnetlib_log_level,
401
+ connection_timeout)
402
+ return self._cache.register(self._conn, alias)
403
+
404
+ def _parse_window_size(self, window_size):
405
+ if not window_size:
406
+ return None
407
+ try:
408
+ cols, rows = window_size.split('x', 1)
409
+ return int(cols), int(rows)
410
+ except ValueError:
411
+ raise ValueError("Invalid window size '%s'. Should be "
412
+ "<columns>x<rows>." % window_size)
413
+
414
+ def _get_connection(self, *args):
415
+ """Can be overridden to use a custom connection."""
416
+ return TelnetConnection(*args)
417
+
418
+ def _set_connection_timeout(self, connection_timeout):
419
+ self._connection_timeout = connection_timeout
420
+ if self._connection_timeout:
421
+ self._connection_timeout = timestr_to_secs(connection_timeout)
422
+
423
+ def switch_connection(self, index_or_alias):
424
+ """Switches between active connections using an index or an alias.
425
+
426
+ Aliases can be given to `Open Connection` keyword which also always
427
+ returns the connection index.
428
+
429
+ This keyword returns the index of previous active connection.
430
+
431
+ Example:
432
+ | `Open Connection` | myhost.net | | |
433
+ | `Login` | john | secret | |
434
+ | `Write` | some command | | |
435
+ | `Open Connection` | yourhost.com | 2nd conn | |
436
+ | `Login` | root | password | |
437
+ | `Write` | another cmd | | |
438
+ | ${old index}= | `Switch Connection` | 1 | # index |
439
+ | `Write` | something | | |
440
+ | `Switch Connection` | 2nd conn | | # alias |
441
+ | `Write` | whatever | | |
442
+ | `Switch Connection` | ${old index} | | # back to original |
443
+ | [Teardown] | `Close All Connections` | | |
444
+
445
+ The example above expects that there were no other open
446
+ connections when opening the first one, because it used index
447
+ ``1`` when switching to the connection later. If you are not
448
+ sure about that, you can store the index into a variable as
449
+ shown below.
450
+
451
+ | ${index} = | `Open Connection` | myhost.net |
452
+ | `Do Something` | | |
453
+ | `Switch Connection` | ${index} | |
454
+ """
455
+ old_index = self._cache.current_index
456
+ self._conn = self._cache.switch(index_or_alias)
457
+ return old_index
458
+
459
+ def close_all_connections(self):
460
+ """Closes all open connections and empties the connection cache.
461
+
462
+ If multiple connections are opened, this keyword should be used in
463
+ a test or suite teardown to make sure that all connections are closed.
464
+ It is not an error if some of the connections have already been closed
465
+ by `Close Connection`.
466
+
467
+ After this keyword, new indexes returned by `Open Connection`
468
+ keyword are reset to 1.
469
+ """
470
+ self._conn = self._cache.close_all()
471
+
472
+
473
+ class TelnetConnection(telnetlib.Telnet):
474
+ NEW_ENVIRON_IS = b'\x00'
475
+ NEW_ENVIRON_VAR = b'\x00'
476
+ NEW_ENVIRON_VALUE = b'\x01'
477
+ INTERNAL_UPDATE_FREQUENCY = 0.03
478
+
479
+ def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF',
480
+ prompt=None, prompt_is_regexp=False,
481
+ encoding='UTF-8', encoding_errors='ignore',
482
+ default_log_level='INFO', window_size=None, environ_user=None,
483
+ terminal_emulation=False, terminal_type=None,
484
+ telnetlib_log_level='TRACE', connection_timeout=None):
485
+ if connection_timeout is None:
486
+ telnetlib.Telnet.__init__(self, host, int(port) if port else 23)
487
+ else:
488
+ telnetlib.Telnet.__init__(self, host, int(port) if port else 23,
489
+ connection_timeout)
490
+ self._set_timeout(timeout)
491
+ self._set_newline(newline)
492
+ self._set_prompt(prompt, prompt_is_regexp)
493
+ self._set_encoding(encoding, encoding_errors)
494
+ self._set_default_log_level(default_log_level)
495
+ self._window_size = window_size
496
+ self._environ_user = self._encode(environ_user) if environ_user else None
497
+ self._terminal_emulator = self._check_terminal_emulation(terminal_emulation)
498
+ self._terminal_type = self._encode(terminal_type) if terminal_type else None
499
+ self.set_option_negotiation_callback(self._negotiate_options)
500
+ self._set_telnetlib_log_level(telnetlib_log_level)
501
+ self._opt_responses = list()
502
+
503
+ def set_timeout(self, timeout):
504
+ """Sets the timeout used for waiting output in the current connection.
505
+
506
+ Read operations that expect some output to appear (`Read Until`, `Read
507
+ Until Regexp`, `Read Until Prompt`, `Login`) use this timeout and fail
508
+ if the expected output does not appear before this timeout expires.
509
+
510
+ The ``timeout`` must be given in `time string format`. The old timeout
511
+ is returned and can be used to restore the timeout later.
512
+
513
+ Example:
514
+ | ${old} = | `Set Timeout` | 2 minute 30 seconds |
515
+ | `Do Something` |
516
+ | `Set Timeout` | ${old} |
517
+
518
+ See `Configuration` section for more information about global and
519
+ connection specific configuration.
520
+ """
521
+ self._verify_connection()
522
+ old = self._timeout
523
+ self._set_timeout(timeout)
524
+ return secs_to_timestr(old)
525
+
526
+ def _set_timeout(self, timeout):
527
+ self._timeout = timestr_to_secs(timeout)
528
+
529
+ def set_newline(self, newline):
530
+ """Sets the newline used by `Write` keyword in the current connection.
531
+
532
+ The old newline is returned and can be used to restore the newline later.
533
+ See `Set Timeout` for a similar example.
534
+
535
+ If terminal emulation is used, the newline can not be changed on an open
536
+ connection.
537
+
538
+ See `Configuration` section for more information about global and
539
+ connection specific configuration.
540
+ """
541
+ self._verify_connection()
542
+ if self._terminal_emulator:
543
+ raise AssertionError("Newline can not be changed when terminal emulation is used.")
544
+ old = self._newline
545
+ self._set_newline(newline)
546
+ return old
547
+
548
+ def _set_newline(self, newline):
549
+ newline = str(newline).upper()
550
+ self._newline = newline.replace('LF', '\n').replace('CR', '\r')
551
+
552
+ def set_prompt(self, prompt, prompt_is_regexp=False):
553
+ """Sets the prompt used by `Read Until Prompt` and `Login` in the current connection.
554
+
555
+ If ``prompt_is_regexp`` is given a true value (see `Boolean arguments`),
556
+ the given ``prompt`` is considered to be a regular expression.
557
+
558
+ The old prompt is returned and can be used to restore the prompt later.
559
+
560
+ Example:
561
+ | ${prompt} | ${regexp} = | `Set Prompt` | $ |
562
+ | `Do Something` |
563
+ | `Set Prompt` | ${prompt} | ${regexp} |
564
+
565
+ See the documentation of
566
+ [http://docs.python.org/library/re.html|Python re module]
567
+ for more information about the supported regular expression syntax.
568
+ Notice that possible backslashes need to be escaped in Robot Framework data.
569
+
570
+ See `Configuration` section for more information about global and
571
+ connection specific configuration.
572
+ """
573
+ self._verify_connection()
574
+ old = self._prompt
575
+ self._set_prompt(prompt, prompt_is_regexp)
576
+ if old[1]:
577
+ return old[0].pattern, True
578
+ return old
579
+
580
+ def _set_prompt(self, prompt, prompt_is_regexp):
581
+ if is_truthy(prompt_is_regexp):
582
+ self._prompt = (re.compile(prompt), True)
583
+ else:
584
+ self._prompt = (prompt, False)
585
+
586
+ def _prompt_is_set(self):
587
+ return self._prompt[0] is not None
588
+
589
+ @keyword(types=None)
590
+ def set_encoding(self, encoding=None, errors=None):
591
+ """Sets the encoding to use for `writing and reading` in the current connection.
592
+
593
+ The given ``encoding`` specifies the encoding to use when written/read
594
+ text is encoded/decoded, and ``errors`` specifies the error handler to
595
+ use if encoding/decoding fails. Either of these can be omitted and in
596
+ that case the old value is not affected. Use string ``NONE`` to disable
597
+ encoding altogether.
598
+
599
+ See `Configuration` section for more information about encoding and
600
+ error handlers, as well as global and connection specific configuration
601
+ in general.
602
+
603
+ The old values are returned and can be used to restore the encoding
604
+ and the error handler later. See `Set Prompt` for a similar example.
605
+
606
+ If terminal emulation is used, the encoding can not be changed on an open
607
+ connection.
608
+ """
609
+ self._verify_connection()
610
+ if self._terminal_emulator:
611
+ raise AssertionError("Encoding can not be changed when terminal emulation is used.")
612
+ old = self._encoding
613
+ self._set_encoding(encoding or old[0], errors or old[1])
614
+ return old
615
+
616
+ def _set_encoding(self, encoding, errors):
617
+ self._encoding = (encoding.upper(), errors)
618
+
619
+ def _encode(self, text):
620
+ if is_bytes(text):
621
+ return text
622
+ if self._encoding[0] == 'NONE':
623
+ return text.encode('ASCII')
624
+ return text.encode(*self._encoding)
625
+
626
+ def _decode(self, bytes):
627
+ if self._encoding[0] == 'NONE':
628
+ return bytes
629
+ return bytes.decode(*self._encoding)
630
+
631
+ def set_telnetlib_log_level(self, level):
632
+ """Sets the log level used for `logging` in the underlying ``telnetlib``.
633
+
634
+ Note that ``telnetlib`` can be very noisy thus using the level ``NONE``
635
+ can shutdown the messages generated by this library.
636
+ """
637
+ self._verify_connection()
638
+ old = self._telnetlib_log_level
639
+ self._set_telnetlib_log_level(level)
640
+ return old
641
+
642
+ def _set_telnetlib_log_level(self, level):
643
+ if level.upper() == 'NONE':
644
+ self._telnetlib_log_level = 'NONE'
645
+ elif self._is_valid_log_level(level) is False:
646
+ raise AssertionError("Invalid log level '%s'" % level)
647
+ self._telnetlib_log_level = level.upper()
648
+
649
+ def set_default_log_level(self, level):
650
+ """Sets the default log level used for `logging` in the current connection.
651
+
652
+ The old default log level is returned and can be used to restore the
653
+ log level later.
654
+
655
+ See `Configuration` section for more information about global and
656
+ connection specific configuration.
657
+ """
658
+ self._verify_connection()
659
+ old = self._default_log_level
660
+ self._set_default_log_level(level)
661
+ return old
662
+
663
+ def _set_default_log_level(self, level):
664
+ if level is None or not self._is_valid_log_level(level):
665
+ raise AssertionError("Invalid log level '%s'" % level)
666
+ self._default_log_level = level.upper()
667
+
668
+ def _is_valid_log_level(self, level):
669
+ if level is None:
670
+ return True
671
+ if not is_string(level):
672
+ return False
673
+ return level.upper() in ('TRACE', 'DEBUG', 'INFO', 'WARN')
674
+
675
+ def close_connection(self, loglevel=None):
676
+ """Closes the current Telnet connection.
677
+
678
+ Remaining output in the connection is read, logged, and returned.
679
+ It is not an error to close an already closed connection.
680
+
681
+ Use `Close All Connections` if you want to make sure all opened
682
+ connections are closed.
683
+
684
+ See `Logging` section for more information about log levels.
685
+ """
686
+ if self.sock:
687
+ self.sock.shutdown(socket.SHUT_RDWR)
688
+ self.close()
689
+ output = self._decode(self.read_all())
690
+ self._log(output, loglevel)
691
+ return output
692
+
693
+ def login(self, username, password, login_prompt='login: ',
694
+ password_prompt='Password: ', login_timeout='1 second',
695
+ login_incorrect='Login incorrect'):
696
+ """Logs in to the Telnet server with the given user information.
697
+
698
+ This keyword reads from the connection until the ``login_prompt`` is
699
+ encountered and then types the given ``username``. Then it reads until
700
+ the ``password_prompt`` and types the given ``password``. In both cases
701
+ a newline is appended automatically and the connection specific
702
+ timeout used when waiting for outputs.
703
+
704
+ How logging status is verified depends on whether a prompt is set for
705
+ this connection or not:
706
+
707
+ 1) If the prompt is set, this keyword reads the output until the prompt
708
+ is found using the normal timeout. If no prompt is found, login is
709
+ considered failed and also this keyword fails. Note that in this case
710
+ both ``login_timeout`` and ``login_incorrect`` arguments are ignored.
711
+
712
+ 2) If the prompt is not set, this keywords sleeps until ``login_timeout``
713
+ and then reads all the output available on the connection. If the
714
+ output contains ``login_incorrect`` text, login is considered failed
715
+ and also this keyword fails.
716
+
717
+ See `Configuration` section for more information about setting
718
+ newline, timeout, and prompt.
719
+ """
720
+ output = self._submit_credentials(username, password, login_prompt,
721
+ password_prompt)
722
+ if self._prompt_is_set():
723
+ success, output2 = self._read_until_prompt()
724
+ else:
725
+ success, output2 = self._verify_login_without_prompt(
726
+ login_timeout, login_incorrect)
727
+ output += output2
728
+ self._log(output)
729
+ if not success:
730
+ raise AssertionError('Login incorrect')
731
+ return output
732
+
733
+ def _submit_credentials(self, username, password, login_prompt, password_prompt):
734
+ # Using write_bare here instead of write because don't want to wait for
735
+ # newline: https://github.com/robotframework/robotframework/issues/1371
736
+ output = self.read_until(login_prompt, 'TRACE')
737
+ self.write_bare(username + self._newline)
738
+ output += self.read_until(password_prompt, 'TRACE')
739
+ self.write_bare(password + self._newline)
740
+ return output
741
+
742
+ def _verify_login_without_prompt(self, delay, incorrect):
743
+ time.sleep(timestr_to_secs(delay))
744
+ output = self.read('TRACE')
745
+ success = incorrect not in output
746
+ return success, output
747
+
748
+ def write(self, text, loglevel=None):
749
+ """Writes the given text plus a newline into the connection.
750
+
751
+ The newline character sequence to use can be [#Configuration|configured]
752
+ both globally and per connection basis. The default value is ``CRLF``.
753
+
754
+ This keyword consumes the written text, until the added newline, from
755
+ the output and logs and returns it. The given text itself must not
756
+ contain newlines. Use `Write Bare` instead if either of these features
757
+ causes a problem.
758
+
759
+ *Note:* This keyword does not return the possible output of the executed
760
+ command. To get the output, one of the `Read ...` `keywords` must be
761
+ used. See `Writing and reading` section for more details.
762
+
763
+ See `Logging` section for more information about log levels.
764
+ """
765
+ newline = self._get_newline_for(text)
766
+ if newline in text:
767
+ raise RuntimeError("'Write' keyword cannot be used with strings "
768
+ "containing newlines. Use 'Write Bare' instead.")
769
+ self.write_bare(text + newline)
770
+ # Can't read until 'text' because long lines are cut strangely in the output
771
+ return self.read_until(self._newline, loglevel)
772
+
773
+ def _get_newline_for(self, text):
774
+ if is_bytes(text):
775
+ return self._encode(self._newline)
776
+ return self._newline
777
+
778
+ def write_bare(self, text, char_delay=None):
779
+ """Writes the given text, and nothing else, into the connection.
780
+
781
+ If ``char_delay`` is specified, the text is sent character by
782
+ character with the given delay, in seconds, between them.
783
+
784
+ This keyword does not append a newline nor consume the written text.
785
+ Use `Write` if these features are needed.
786
+ """
787
+ self._verify_connection()
788
+ if char_delay:
789
+ for ch in list(text):
790
+ telnetlib.Telnet.write(self, self._encode(ch))
791
+ time.sleep(float(char_delay))
792
+ else:
793
+ telnetlib.Telnet.write(self, self._encode(text))
794
+
795
+ def write_until_expected_output(self, text, expected, timeout,
796
+ retry_interval, loglevel=None):
797
+ """Writes the given ``text`` repeatedly, until ``expected`` appears in the output.
798
+
799
+ ``text`` is written without appending a newline and it is consumed from
800
+ the output before trying to find ``expected``. If ``expected`` does not
801
+ appear in the output within ``timeout``, this keyword fails.
802
+
803
+ ``retry_interval`` defines the time to wait ``expected`` to appear before
804
+ writing the ``text`` again. Consuming the written ``text`` is subject to
805
+ the normal [#Configuration|configured timeout].
806
+
807
+ Both ``timeout`` and ``retry_interval`` must be given in `time string
808
+ format`. See `Logging` section for more information about log levels.
809
+
810
+ Example:
811
+ | Write Until Expected Output | ps -ef| grep myprocess\\r\\n | myprocess |
812
+ | ... | 5 s | 0.5 s |
813
+
814
+ The above example writes command ``ps -ef | grep myprocess\\r\\n`` until
815
+ ``myprocess`` appears in the output. The command is written every 0.5
816
+ seconds and the keyword fails if ``myprocess`` does not appear in
817
+ the output in 5 seconds.
818
+ """
819
+ timeout = timestr_to_secs(timeout)
820
+ retry_interval = timestr_to_secs(retry_interval)
821
+ maxtime = time.time() + timeout
822
+ while time.time() < maxtime:
823
+ self.write_bare(text)
824
+ self.read_until(text, loglevel)
825
+ try:
826
+ with self._custom_timeout(retry_interval):
827
+ return self.read_until(expected, loglevel)
828
+ except AssertionError:
829
+ pass
830
+ raise NoMatchError(expected, timeout)
831
+
832
+ def write_control_character(self, character):
833
+ """Writes the given control character into the connection.
834
+
835
+ The control character is prepended with an IAC (interpret as command)
836
+ character.
837
+
838
+ The following control character names are supported: BRK, IP, AO, AYT,
839
+ EC, EL, NOP. Additionally, you can use arbitrary numbers to send any
840
+ control character.
841
+
842
+ Example:
843
+ | Write Control Character | BRK | # Send Break command |
844
+ | Write Control Character | 241 | # Send No operation command |
845
+ """
846
+ self._verify_connection()
847
+ self.sock.sendall(telnetlib.IAC + self._get_control_character(character))
848
+
849
+ def _get_control_character(self, int_or_name):
850
+ try:
851
+ ordinal = int(int_or_name)
852
+ return bytes(bytearray([ordinal]))
853
+ except ValueError:
854
+ return self._convert_control_code_name_to_character(int_or_name)
855
+
856
+ def _convert_control_code_name_to_character(self, name):
857
+ code_names = {
858
+ 'BRK' : telnetlib.BRK,
859
+ 'IP' : telnetlib.IP,
860
+ 'AO' : telnetlib.AO,
861
+ 'AYT' : telnetlib.AYT,
862
+ 'EC' : telnetlib.EC,
863
+ 'EL' : telnetlib.EL,
864
+ 'NOP' : telnetlib.NOP
865
+ }
866
+ try:
867
+ return code_names[name]
868
+ except KeyError:
869
+ raise RuntimeError("Unsupported control character '%s'." % name)
870
+
871
+ def read(self, loglevel=None):
872
+ """Reads everything that is currently available in the output.
873
+
874
+ Read output is both returned and logged. See `Logging` section for more
875
+ information about log levels.
876
+ """
877
+ self._verify_connection()
878
+ output = self._decode(self.read_very_eager())
879
+ if self._terminal_emulator:
880
+ self._terminal_emulator.feed(output)
881
+ output = self._terminal_emulator.read()
882
+ self._log(output, loglevel)
883
+ return output
884
+
885
+ def read_until(self, expected, loglevel=None):
886
+ """Reads output until ``expected`` text is encountered.
887
+
888
+ Text up to and including the match is returned and logged. If no match
889
+ is found, this keyword fails. How much to wait for the output depends
890
+ on the [#Configuration|configured timeout].
891
+
892
+ See `Logging` section for more information about log levels. Use
893
+ `Read Until Regexp` if more complex matching is needed.
894
+ """
895
+ success, output = self._read_until(expected)
896
+ self._log(output, loglevel)
897
+ if not success:
898
+ raise NoMatchError(expected, self._timeout, output)
899
+ return output
900
+
901
+ def _read_until(self, expected):
902
+ self._verify_connection()
903
+ if self._terminal_emulator:
904
+ return self._terminal_read_until(expected)
905
+ expected = self._encode(expected)
906
+ output = telnetlib.Telnet.read_until(self, expected, self._timeout)
907
+ return output.endswith(expected), self._decode(output)
908
+
909
+ @property
910
+ def _terminal_frequency(self):
911
+ return min(self.INTERNAL_UPDATE_FREQUENCY, self._timeout)
912
+
913
+ def _terminal_read_until(self, expected):
914
+ max_time = time.time() + self._timeout
915
+ output = self._terminal_emulator.read_until(expected)
916
+ if output:
917
+ return True, output
918
+ while time.time() < max_time:
919
+ output = telnetlib.Telnet.read_until(self, self._encode(expected),
920
+ self._terminal_frequency)
921
+ self._terminal_emulator.feed(self._decode(output))
922
+ output = self._terminal_emulator.read_until(expected)
923
+ if output:
924
+ return True, output
925
+ return False, self._terminal_emulator.read()
926
+
927
+ def _read_until_regexp(self, *expected):
928
+ self._verify_connection()
929
+ if self._terminal_emulator:
930
+ return self._terminal_read_until_regexp(expected)
931
+ expected = [self._encode(exp) if is_string(exp) else exp
932
+ for exp in expected]
933
+ return self._telnet_read_until_regexp(expected)
934
+
935
+ def _terminal_read_until_regexp(self, expected_list):
936
+ max_time = time.time() + self._timeout
937
+ regexps_bytes = [self._to_byte_regexp(rgx) for rgx in expected_list]
938
+ regexps_unicode = [re.compile(self._decode(rgx.pattern))
939
+ for rgx in regexps_bytes]
940
+ out = self._terminal_emulator.read_until_regexp(regexps_unicode)
941
+ if out:
942
+ return True, out
943
+ while time.time() < max_time:
944
+ output = self.expect(regexps_bytes, self._terminal_frequency)[-1]
945
+ self._terminal_emulator.feed(self._decode(output))
946
+ out = self._terminal_emulator.read_until_regexp(regexps_unicode)
947
+ if out:
948
+ return True, out
949
+ return False, self._terminal_emulator.read()
950
+
951
+ def _telnet_read_until_regexp(self, expected_list):
952
+ expected = [self._to_byte_regexp(exp) for exp in expected_list]
953
+ try:
954
+ index, _, output = self.expect(expected, self._timeout)
955
+ except TypeError:
956
+ index, output = -1, b''
957
+ return index != -1, self._decode(output)
958
+
959
+ def _to_byte_regexp(self, exp):
960
+ if is_bytes(exp):
961
+ return re.compile(exp)
962
+ if is_string(exp):
963
+ return re.compile(self._encode(exp))
964
+ pattern = exp.pattern
965
+ if is_bytes(pattern):
966
+ return exp
967
+ return re.compile(self._encode(pattern))
968
+
969
+ def read_until_regexp(self, *expected):
970
+ """Reads output until any of the ``expected`` regular expressions match.
971
+
972
+ This keyword accepts any number of regular expressions patterns or
973
+ compiled Python regular expression objects as arguments. Text up to
974
+ and including the first match to any of the regular expressions is
975
+ returned and logged. If no match is found, this keyword fails. How much
976
+ to wait for the output depends on the [#Configuration|configured timeout].
977
+
978
+ If the last given argument is a [#Logging|valid log level], it is used
979
+ as ``loglevel`` similarly as with `Read Until` keyword.
980
+
981
+ See the documentation of
982
+ [http://docs.python.org/library/re.html|Python re module]
983
+ for more information about the supported regular expression syntax.
984
+ Notice that possible backslashes need to be escaped in Robot Framework data.
985
+
986
+ Examples:
987
+ | `Read Until Regexp` | (#|$) |
988
+ | `Read Until Regexp` | first_regexp | second_regexp |
989
+ | `Read Until Regexp` | \\\\d{4}-\\\\d{2}-\\\\d{2} | DEBUG |
990
+ """
991
+ if not expected:
992
+ raise RuntimeError('At least one pattern required')
993
+ if self._is_valid_log_level(expected[-1]):
994
+ loglevel = expected[-1]
995
+ expected = expected[:-1]
996
+ else:
997
+ loglevel = None
998
+ success, output = self._read_until_regexp(*expected)
999
+ self._log(output, loglevel)
1000
+ if not success:
1001
+ expected = [exp if is_string(exp) else exp.pattern
1002
+ for exp in expected]
1003
+ raise NoMatchError(expected, self._timeout, output)
1004
+ return output
1005
+
1006
+ def read_until_prompt(self, loglevel=None, strip_prompt=False):
1007
+ """Reads output until the prompt is encountered.
1008
+
1009
+ This keyword requires the prompt to be [#Configuration|configured]
1010
+ either in `importing` or with `Open Connection` or `Set Prompt` keyword.
1011
+
1012
+ By default, text up to and including the prompt is returned and logged.
1013
+ If no prompt is found, this keyword fails. How much to wait for the
1014
+ output depends on the [#Configuration|configured timeout].
1015
+
1016
+ If you want to exclude the prompt from the returned output, set
1017
+ ``strip_prompt`` to a true value (see `Boolean arguments`). If your
1018
+ prompt is a regular expression, make sure that the expression spans the
1019
+ whole prompt, because only the part of the output that matches the
1020
+ regular expression is stripped away.
1021
+
1022
+ See `Logging` section for more information about log levels.
1023
+ """
1024
+ if not self._prompt_is_set():
1025
+ raise RuntimeError('Prompt is not set.')
1026
+ success, output = self._read_until_prompt()
1027
+ self._log(output, loglevel)
1028
+ if not success:
1029
+ prompt, regexp = self._prompt
1030
+ raise AssertionError("Prompt '%s' not found in %s."
1031
+ % (prompt if not regexp else prompt.pattern,
1032
+ secs_to_timestr(self._timeout)))
1033
+ if is_truthy(strip_prompt):
1034
+ output = self._strip_prompt(output)
1035
+ return output
1036
+
1037
+ def _read_until_prompt(self):
1038
+ prompt, regexp = self._prompt
1039
+ read_until = self._read_until_regexp if regexp else self._read_until
1040
+ return read_until(prompt)
1041
+
1042
+ def _strip_prompt(self, output):
1043
+ prompt, regexp = self._prompt
1044
+ if not regexp:
1045
+ length = len(prompt)
1046
+ else:
1047
+ match = prompt.search(output)
1048
+ length = match.end() - match.start()
1049
+ return output[:-length]
1050
+
1051
+ def execute_command(self, command, loglevel=None, strip_prompt=False):
1052
+ """Executes the given ``command`` and reads, logs, and returns everything until the prompt.
1053
+
1054
+ This keyword requires the prompt to be [#Configuration|configured]
1055
+ either in `importing` or with `Open Connection` or `Set Prompt` keyword.
1056
+
1057
+ This is a convenience keyword that uses `Write` and `Read Until Prompt`
1058
+ internally. Following two examples are thus functionally identical:
1059
+
1060
+ | ${out} = | `Execute Command` | pwd |
1061
+
1062
+ | `Write` | pwd |
1063
+ | ${out} = | `Read Until Prompt` |
1064
+
1065
+ See `Logging` section for more information about log levels and `Read
1066
+ Until Prompt` for more information about the ``strip_prompt`` parameter.
1067
+ """
1068
+ self.write(command, loglevel)
1069
+ return self.read_until_prompt(loglevel, strip_prompt)
1070
+
1071
+ @contextmanager
1072
+ def _custom_timeout(self, timeout):
1073
+ old = self.set_timeout(timeout)
1074
+ try:
1075
+ yield
1076
+ finally:
1077
+ self.set_timeout(old)
1078
+
1079
+ def _verify_connection(self):
1080
+ if not self.sock:
1081
+ raise RuntimeError('No connection open')
1082
+
1083
+ def _log(self, msg, level=None):
1084
+ if is_bytes(msg):
1085
+ # Robot Framework 7 would decode raw bytes as latin-1 in the log.
1086
+ msg = msg.decode('ASCII', 'backslashreplace')
1087
+ msg = msg.strip()
1088
+ if msg:
1089
+ logger.write(msg, level or self._default_log_level)
1090
+
1091
+ def _negotiate_options(self, sock, cmd, opt):
1092
+ # We don't have state changes in our accepted telnet options.
1093
+ # Therefore, we just track if we've already responded to an option. If
1094
+ # this is the case, we must not send any response.
1095
+ if cmd in (telnetlib.DO, telnetlib.DONT, telnetlib.WILL, telnetlib.WONT):
1096
+ if (cmd, opt) in self._opt_responses:
1097
+ return
1098
+ else:
1099
+ self._opt_responses.append((cmd, opt))
1100
+
1101
+ # This is supposed to turn server side echoing on and turn other options off.
1102
+ if opt == telnetlib.ECHO and cmd in (telnetlib.WILL, telnetlib.WONT):
1103
+ self._opt_echo_on(opt)
1104
+ elif cmd == telnetlib.DO and opt == telnetlib.TTYPE and self._terminal_type:
1105
+ self._opt_terminal_type(opt, self._terminal_type)
1106
+ elif cmd == telnetlib.DO and opt == telnetlib.NEW_ENVIRON and self._environ_user:
1107
+ self._opt_environ_user(opt, self._environ_user)
1108
+ elif cmd == telnetlib.DO and opt == telnetlib.NAWS and self._window_size:
1109
+ self._opt_window_size(opt, *self._window_size)
1110
+ elif opt != telnetlib.NOOPT:
1111
+ self._opt_dont_and_wont(cmd, opt)
1112
+
1113
+ def _opt_echo_on(self, opt):
1114
+ return self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt)
1115
+
1116
+ def _opt_terminal_type(self, opt, terminal_type):
1117
+ self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1118
+ self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.TTYPE
1119
+ + self.NEW_ENVIRON_IS + terminal_type
1120
+ + telnetlib.IAC + telnetlib.SE)
1121
+
1122
+ def _opt_environ_user(self, opt, environ_user):
1123
+ self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1124
+ self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NEW_ENVIRON
1125
+ + self.NEW_ENVIRON_IS + self.NEW_ENVIRON_VAR
1126
+ + b"USER" + self.NEW_ENVIRON_VALUE + environ_user
1127
+ + telnetlib.IAC + telnetlib.SE)
1128
+
1129
+ def _opt_window_size(self, opt, window_x, window_y):
1130
+ self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1131
+ self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NAWS
1132
+ + struct.pack('!HH', window_x, window_y)
1133
+ + telnetlib.IAC + telnetlib.SE)
1134
+
1135
+ def _opt_dont_and_wont(self, cmd, opt):
1136
+ if cmd in (telnetlib.DO, telnetlib.DONT):
1137
+ self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
1138
+ elif cmd in (telnetlib.WILL, telnetlib.WONT):
1139
+ self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
1140
+
1141
+ def msg(self, msg, *args):
1142
+ # Forward telnetlib's debug messages to log
1143
+ if self._telnetlib_log_level != 'NONE':
1144
+ logger.write(msg % args, self._telnetlib_log_level)
1145
+
1146
+ def _check_terminal_emulation(self, terminal_emulation):
1147
+ if not terminal_emulation:
1148
+ return False
1149
+ return TerminalEmulator(window_size=self._window_size,
1150
+ newline=self._newline)
1151
+
1152
+
1153
+ class TerminalEmulator:
1154
+
1155
+ def __init__(self, window_size=None, newline="\r\n"):
1156
+ self._columns, self._rows = window_size or (200, 200)
1157
+ self._newline = newline
1158
+ self._stream = pyte.Stream()
1159
+ self._screen = pyte.HistoryScreen(self._columns,
1160
+ self._rows,
1161
+ history=100000)
1162
+ self._stream.attach(self._screen)
1163
+ self._buffer = ''
1164
+ self._whitespace_after_last_feed = ''
1165
+
1166
+ @property
1167
+ def current_output(self):
1168
+ return self._buffer + self._dump_screen()
1169
+
1170
+ def _dump_screen(self):
1171
+ return self._get_history(self._screen) + \
1172
+ self._get_screen(self._screen) + \
1173
+ self._whitespace_after_last_feed
1174
+
1175
+ def _get_history(self, screen):
1176
+ if not screen.history.top:
1177
+ return ''
1178
+ rows = []
1179
+ for row in screen.history.top:
1180
+ # Newer pyte versions store row data in mappings
1181
+ data = (char.data for _, char in sorted(row.items()))
1182
+ rows.append(''.join(data).rstrip())
1183
+ return self._newline.join(rows).rstrip(self._newline) + self._newline
1184
+
1185
+ def _get_screen(self, screen):
1186
+ rows = (row.rstrip() for row in screen.display)
1187
+ return self._newline.join(rows).rstrip(self._newline)
1188
+
1189
+ def feed(self, text):
1190
+ self._stream.feed(text)
1191
+ self._whitespace_after_last_feed = text[len(text.rstrip()):]
1192
+
1193
+ def read(self):
1194
+ current_out = self.current_output
1195
+ self._update_buffer('')
1196
+ return current_out
1197
+
1198
+ def read_until(self, expected):
1199
+ current_out = self.current_output
1200
+ exp_index = current_out.find(expected)
1201
+ if exp_index != -1:
1202
+ self._update_buffer(current_out[exp_index+len(expected):])
1203
+ return current_out[:exp_index+len(expected)]
1204
+ return None
1205
+
1206
+ def read_until_regexp(self, regexp_list):
1207
+ current_out = self.current_output
1208
+ for rgx in regexp_list:
1209
+ match = rgx.search(current_out)
1210
+ if match:
1211
+ self._update_buffer(current_out[match.end():])
1212
+ return current_out[:match.end()]
1213
+ return None
1214
+
1215
+ def _update_buffer(self, terminal_buffer):
1216
+ self._buffer = terminal_buffer
1217
+ self._whitespace_after_last_feed = ''
1218
+ self._screen.reset()
1219
+
1220
+
1221
+ class NoMatchError(AssertionError):
1222
+ ROBOT_SUPPRESS_NAME = True
1223
+
1224
+ def __init__(self, expected, timeout, output=None):
1225
+ self.expected = expected
1226
+ self.timeout = secs_to_timestr(timeout)
1227
+ self.output = output
1228
+ AssertionError.__init__(self, self._get_message())
1229
+
1230
+ def _get_message(self):
1231
+ expected = "'%s'" % self.expected \
1232
+ if is_string(self.expected) \
1233
+ else seq2str(self.expected, lastsep=' or ')
1234
+ msg = "No match found for %s in %s." % (expected, self.timeout)
1235
+ if self.output is not None:
1236
+ msg += ' Output:\n%s' % self.output
1237
+ return msg