16 from contextlib
import contextmanager
32 is_unicode, secs_to_timestr, seq2str, timestr_to_secs)
289 ROBOT_LIBRARY_SCOPE =
'TEST_SUITE'
315 def __init__(self, timeout='3 seconds', newline='CRLF',
316 prompt=None, prompt_is_regexp=False,
317 encoding='UTF-8', encoding_errors='ignore',
318 default_log_level='INFO', window_size=None,
319 environ_user=None, terminal_emulation=False,
320 terminal_type=None, telnetlib_log_level='TRACE',
321 connection_timeout=None):
325 self.
_prompt_prompt = (prompt, prompt_is_regexp)
347 return [name
for name
in dir(source)
348 if self.
_is_keyword_is_keyword(name, source, excluded)]
351 return (name
not in excluded
and
352 not name.startswith(
'_')
and
353 name !=
'get_keyword_names' and
354 inspect.ismethod(getattr(source, name)))
359 excluded = [name
for name
in dir(telnetlib.Telnet())
360 if name
not in [
'write',
'read',
'read_until']]
390 newline=None, prompt=None, prompt_is_regexp=False,
391 encoding=None, encoding_errors=None,
392 default_log_level=None, window_size=None,
393 environ_user=None, terminal_emulation=None,
394 terminal_type=None, telnetlib_log_level=None,
395 connection_timeout=None):
396 timeout = timeout
or self.
_timeout_timeout
398 if connection_timeout
400 newline = newline
or self.
_newline_newline
401 encoding = encoding
or self.
_encoding_encoding
405 environ_user = environ_user
or self.
_environ_user_environ_user
406 if terminal_emulation
is None:
408 terminal_type = terminal_type
or self.
_terminal_type_terminal_type
411 prompt, prompt_is_regexp = self.
_prompt_prompt
412 logger.info(
'Opening connection to %s:%s with prompt: %s%s'
413 % (host, port, prompt,
' (regexp)' if prompt_is_regexp
else ''))
416 encoding, encoding_errors,
424 return self.
_cache_cache.register(self.
_conn_conn, alias)
430 cols, rows = window_size.split(
'x', 1)
431 return int(cols),
int(rows)
433 raise ValueError(
"Invalid window size '%s'. Should be "
434 "<rows>x<columns>." % window_size)
479 old_index = self.
_cache_cache.current_index
480 self.
_conn_conn = self.
_cache_cache.switch(index_or_alias)
498 NEW_ENVIRON_IS = b
'\x00'
499 NEW_ENVIRON_VAR = b
'\x00'
500 NEW_ENVIRON_VALUE = b
'\x01'
501 INTERNAL_UPDATE_FREQUENCY = 0.03
503 def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF',
504 prompt=None, prompt_is_regexp=False,
505 encoding='UTF-8', encoding_errors='ignore',
506 default_log_level='INFO', window_size=None, environ_user=None,
507 terminal_emulation=False, terminal_type=None,
508 telnetlib_log_level='TRACE', connection_timeout=None):
509 if connection_timeout
is None:
510 telnetlib.Telnet.__init__(self, host,
int(port)
if port
else 23)
512 telnetlib.Telnet.__init__(self, host,
int(port)
if port
else 23,
516 self.
_set_prompt_set_prompt(prompt, prompt_is_regexp)
567 raise AssertionError(
"Newline can not be changed when terminal emulation is used.")
573 newline = str(newline).upper()
574 self.
_newline_newline = newline.replace(
'LF',
'\n').replace(
'CR',
'\r')
600 self.
_set_prompt_set_prompt(prompt, prompt_is_regexp)
602 return old[0].pattern,
True
607 self.
_prompt_prompt = (re.compile(prompt),
True)
609 self.
_prompt_prompt = (prompt,
False)
612 return self.
_prompt_prompt[0]
is not None
636 raise AssertionError(
"Encoding can not be changed when terminal emulation is used.")
638 self.
_set_encoding_set_encoding(encoding
or old[0], errors
or old[1])
648 return text.encode(
'ASCII')
649 return text.encode(*self.
_encoding_encoding)
654 return bytes.decode(*self.
_encoding_encoding)
668 if level.upper() ==
'NONE':
698 return level.upper()
in (
'TRACE',
'DEBUG',
'INFO',
'WARN')
712 self.sock.shutdown(socket.SHUT_RDWR)
714 output = self.
_decode_decode(self.read_all())
715 self.
_log_log(output, loglevel)
742 def login(self, username, password, login_prompt='login:
',
743 password_prompt='Password: ', login_timeout=
'1 second',
744 login_incorrect=
'Login incorrect'):
751 login_timeout, login_incorrect)
753 self.
_log_log(output)
761 output = self.
read_untilread_until(login_prompt,
'TRACE')
763 output += self.
read_untilread_until(password_prompt,
'TRACE')
769 output = self.
readread(
'TRACE')
770 success = incorrect
not in output
771 return success, output
789 def write(self, text, loglevel=None):
792 raise RuntimeError(
"'Write' keyword cannot be used with strings "
793 "containing newlines. Use 'Write Bare' instead.")
810 telnetlib.Telnet.write(self, self.
_encode_encode(text))
835 retry_interval, loglevel=None):
838 maxtime = time.time() + timeout
839 while time.time() < maxtime:
844 return self.
read_untilread_until(expected, loglevel)
845 except AssertionError:
868 ordinal =
int(int_or_name)
869 return bytes(bytearray([ordinal]))
875 'BRK' : telnetlib.BRK,
878 'AYT' : telnetlib.AYT,
881 'NOP' : telnetlib.NOP
884 return code_names[name]
886 raise RuntimeError(
"Unsupported control character '%s'." % name)
895 output = self.
_decode_decode(self.read_very_eager())
899 self.
_log_log(output, loglevel)
912 success, output = self.
_read_until_read_until(expected)
913 self.
_log_log(output, loglevel)
922 expected = self.
_encode_encode(expected)
923 output = telnetlib.Telnet.read_until(self, expected, self.
_timeout_timeout)
924 return output.endswith(expected), self.
_decode_decode(output)
927 _terminal_frequency = property
933 max_time = time.time() + self.
_timeout_timeout
937 while time.time() < max_time:
938 output = telnetlib.Telnet.read_until(self, self.
_encode_encode(expected),
955 max_time = time.time() + self.
_timeout_timeout
956 regexps_bytes = [self.
_to_byte_regexp_to_byte_regexp(rgx)
for rgx
in expected_list]
957 regexps_unicode = [re.compile(self.
_decode_decode(rgx.pattern))
958 for rgx
in regexps_bytes]
962 while time.time() < max_time:
971 expected = [self.
_to_byte_regexp_to_byte_regexp(exp)
for exp
in expected_list]
973 index, _, output = self.expect(expected, self.
_timeout_timeout)
975 index, output = -1, b
''
976 return index != -1, self.
_decode_decode(output)
980 return re.compile(exp)
982 return re.compile(self.
_encode_encode(exp))
983 pattern = exp.pattern
986 return re.compile(self.
_encode_encode(pattern))
1012 raise RuntimeError(
'At least one pattern required')
1014 loglevel = expected[-1]
1015 expected = expected[:-1]
1019 self.
_log_log(output, loglevel)
1021 expected = [exp
if is_string(exp)
else exp.pattern
1022 for exp
in expected]
1045 raise RuntimeError(
'Prompt is not set.')
1047 self.
_log_log(output, loglevel)
1049 prompt, regexp = self.
_prompt_prompt
1051 % (prompt
if not regexp
else prompt.pattern,
1058 prompt, regexp = self.
_prompt_prompt
1063 prompt, regexp = self.
_prompt_prompt
1065 length = len(prompt)
1067 match = prompt.search(output)
1068 length = match.end() - match.start()
1069 return output[:-length]
1088 self.
writewrite(command, loglevel)
1101 raise RuntimeError(
'No connection open')
1112 if cmd
in (telnetlib.DO, telnetlib.DONT, telnetlib.WILL, telnetlib.WONT):
1119 if opt == telnetlib.ECHO
and cmd
in (telnetlib.WILL, telnetlib.WONT):
1121 elif cmd == telnetlib.DO
and opt == telnetlib.TTYPE
and self.
_terminal_type_terminal_type:
1123 elif cmd == telnetlib.DO
and opt == telnetlib.NEW_ENVIRON
and self.
_environ_user_environ_user:
1125 elif cmd == telnetlib.DO
and opt == telnetlib.NAWS
and self.
_window_size_window_size:
1127 elif opt != telnetlib.NOOPT:
1131 return self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt)
1134 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1135 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.TTYPE
1137 + telnetlib.IAC + telnetlib.SE)
1140 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1141 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NEW_ENVIRON
1144 + telnetlib.IAC + telnetlib.SE)
1147 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1148 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NAWS
1149 + struct.pack(
'!HH', window_x, window_y)
1150 + telnetlib.IAC + telnetlib.SE)
1153 if cmd
in (telnetlib.DO, telnetlib.DONT):
1154 self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
1155 elif cmd
in (telnetlib.WILL, telnetlib.WONT):
1156 self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
1164 if not terminal_emulation:
1167 raise RuntimeError(
"Terminal emulation requires pyte module!\n"
1168 "http://pypi.python.org/pypi/pyte/")
1176 self._rows, self.
_columns_columns = window_size
or (200, 200)
1179 self.
_screen_screen = pyte.HistoryScreen(self._rows,
1187 current_output = property
1198 if not screen.history.top:
1201 for row
in screen.history.top:
1203 data = (char.data
for _, char
in sorted(row.items()))
1204 rows.append(
''.join(data).rstrip())
1208 rows = (row.rstrip()
for row
in screen.display)
1222 exp_index = current_out.find(expected)
1224 self.
_update_buffer_update_buffer(current_out[exp_index+len(expected):])
1225 return current_out[:exp_index+len(expected)]
1230 for rgx
in regexp_list:
1231 match = rgx.search(current_out)
1234 return current_out[:match.end()]
1238 self.
_buffer_buffer = terminal_buffer
1244 ROBOT_SUPPRESS_NAME =
True
1250 AssertionError.__init__(self, self.
_get_message_get_message())
1253 expected =
"'%s'" % self.
expectedexpected \
1256 msg =
"No match found for %s in %s." % (expected, self.
timeouttimeout)
1257 if self.
outputoutput
is not None:
1258 msg +=
' Output:\n%s' % self.
outputoutput
def __init__(self, expected, timeout, output=None)
def _opt_window_size(self, opt, window_x, window_y)
def _log(self, msg, level=None)
def _opt_echo_on(self, opt)
def msg(self, msg, *args)
def _strip_prompt(self, output)
def _is_valid_log_level(self, level)
def _submit_credentials(self, username, password, login_prompt, password_prompt)
def _terminal_read_until(self, expected)
def execute_command(self, command, loglevel=None, strip_prompt=False)
Executes the given command and reads, logs, and returns everything until the prompt.
def read_until(self, expected, loglevel=None)
Reads output until expected text is encountered.
def _convert_control_code_name_to_character(self, name)
def _opt_dont_and_wont(self, cmd, opt)
def _opt_environ_user(self, opt, environ_user)
def set_telnetlib_log_level(self, level)
Sets the log level used for logging in the underlying telnetlib.
def _get_control_character(self, int_or_name)
def _read_until(self, expected)
def set_encoding(self, encoding=None, errors=None)
Sets the encoding to use for writing and reading in the current connection.
def _set_encoding(self, encoding, errors)
def _to_byte_regexp(self, exp)
def read_until_regexp(self, *expected)
Reads output until any of the expected regular expressions match.
def set_timeout(self, timeout)
Sets the timeout used for waiting output in the current connection.
def set_prompt(self, prompt, prompt_is_regexp=False)
Sets the prompt used by Read Until Prompt and Login in the current connection.
def set_newline(self, newline)
Sets the newline used by Write keyword in the current connection.
def _get_newline_for(self, text)
def _set_prompt(self, prompt, prompt_is_regexp)
def set_default_log_level(self, level)
Sets the default log level used for logging in the current connection.
def _set_default_log_level(self, level)
def read(self, loglevel=None)
Reads everything that is currently available in the output.
def _verify_connection(self)
def _check_terminal_emulation(self, terminal_emulation)
def _terminal_read_until_regexp(self, expected_list)
def _opt_terminal_type(self, opt, terminal_type)
def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF', prompt=None, prompt_is_regexp=False, encoding='UTF-8', encoding_errors='ignore', default_log_level='INFO', window_size=None, environ_user=None, terminal_emulation=False, terminal_type=None, telnetlib_log_level='TRACE', connection_timeout=None)
def _custom_timeout(self, timeout)
def login(self, username, password, login_prompt='login:', password_prompt='Password:', login_timeout='1 second', login_incorrect='Login incorrect')
Logs in to the Telnet server with the given user information.
def _negotiate_options(self, sock, cmd, opt)
def _set_timeout(self, timeout)
def _read_until_regexp(self, *expected)
def _read_until_prompt(self)
def _terminal_frequency(self)
def write(self, text, loglevel=None)
Writes the given text plus a newline into the connection.
def _set_newline(self, newline)
def _telnet_read_until_regexp(self, expected_list)
def _set_telnetlib_log_level(self, level)
def write_until_expected_output(self, text, expected, timeout, retry_interval, loglevel=None)
Writes the given text repeatedly, until expected appears in the output.
def _verify_login_without_prompt(self, delay, incorrect)
def close_connection(self, loglevel=None)
Closes the current Telnet connection.
def read_until_prompt(self, loglevel=None, strip_prompt=False)
Reads output until the prompt is encountered.
float INTERNAL_UPDATE_FREQUENCY
def write_bare(self, text)
Writes the given text, and nothing else, into the connection.
def write_control_character(self, character)
Writes the given control character into the connection.
A test library providing communication over Telnet connections.
def _parse_window_size(self, window_size)
def __init__(self, timeout='3 seconds', newline='CRLF', prompt=None, prompt_is_regexp=False, encoding='UTF-8', encoding_errors='ignore', default_log_level='INFO', window_size=None, environ_user=None, terminal_emulation=False, terminal_type=None, telnetlib_log_level='TRACE', connection_timeout=None)
Telnet library can be imported with optional configuration parameters.
def _get_keywords(self, source, excluded)
def _get_library_keywords(self)
def close_all_connections(self)
Closes all open connections and empties the connection cache.
def __getattr__(self, name)
def _get_connection(self, *args)
Can be overridden to use a custom connection.
def switch_connection(self, index_or_alias)
Switches between active connections using an index or an alias.
def get_keyword_names(self)
def _is_keyword(self, name, source, excluded)
def _get_connection_keywords(self)
def _set_connection_timeout(self, connection_timeout)
def open_connection(self, host, alias=None, port=23, timeout=None, newline=None, prompt=None, prompt_is_regexp=False, encoding=None, encoding_errors=None, default_log_level=None, window_size=None, environ_user=None, terminal_emulation=None, terminal_type=None, telnetlib_log_level=None, connection_timeout=None)
Opens a new Telnet connection to the given host and port.
def __init__(self, window_size=None, newline="\r\n")
def _get_history(self, screen)
def _get_screen(self, screen)
_whitespace_after_last_feed
def read_until(self, expected)
def _update_buffer(self, terminal_buffer)
def read_until_regexp(self, regexp_list)
def seq2str(sequence, quote="'", sep=', ', lastsep=' and ')
Returns sequence in format ‘'item 1’, 'item 2' and 'item 3'`.
def secs_to_timestr(secs, compact=False)
Converts time in seconds to a string representation.
def timestr_to_secs(timestr, round_to=3)
Parses time like '1h 10s', '01:00:10' or '42' and returns seconds.
def is_truthy(item)
Returns True or False depending is the item considered true or not.
def get_version(naked=False)