16 from contextlib
import contextmanager
31 from robot.utils import (ConnectionCache, is_bytes, is_string, is_truthy,
32 secs_to_timestr, seq2str, timestr_to_secs)
278 ROBOT_LIBRARY_SCOPE =
'SUITE'
304 def __init__(self, timeout='3 seconds', newline='CRLF',
305 prompt=None, prompt_is_regexp=False,
306 encoding='UTF-8', encoding_errors='ignore',
307 default_log_level='INFO', window_size=None,
308 environ_user=None, terminal_emulation=False,
309 terminal_type=None, telnetlib_log_level='TRACE',
310 connection_timeout=None):
314 self.
_prompt_prompt = (prompt, prompt_is_regexp)
336 return [name
for name
in dir(source)
337 if self.
_is_keyword_is_keyword(name, source, excluded)]
340 return (name
not in excluded
and
341 not name.startswith(
'_')
and
342 name !=
'get_keyword_names' and
343 inspect.ismethod(getattr(source, name)))
348 excluded = [name
for name
in dir(telnetlib.Telnet())
349 if name
not in [
'write',
'read',
'read_until']]
379 newline=None, prompt=None, prompt_is_regexp=False,
380 encoding=None, encoding_errors=None,
381 default_log_level=None, window_size=None,
382 environ_user=None, terminal_emulation=None,
383 terminal_type=None, telnetlib_log_level=None,
384 connection_timeout=None):
385 timeout = timeout
or self.
_timeout_timeout
387 if connection_timeout
389 newline = newline
or self.
_newline_newline
390 encoding = encoding
or self.
_encoding_encoding
394 environ_user = environ_user
or self.
_environ_user_environ_user
395 if terminal_emulation
is None:
397 terminal_type = terminal_type
or self.
_terminal_type_terminal_type
400 prompt, prompt_is_regexp = self.
_prompt_prompt
401 logger.info(
'Opening connection to %s:%s with prompt: %s%s'
402 % (host, port, prompt,
' (regexp)' if prompt_is_regexp
else ''))
405 encoding, encoding_errors,
413 return self.
_cache_cache.register(self.
_conn_conn, alias)
419 cols, rows = window_size.split(
'x', 1)
420 return int(cols), int(rows)
422 raise ValueError(
"Invalid window size '%s'. Should be "
423 "<rows>x<columns>." % window_size)
468 old_index = self.
_cache_cache.current_index
469 self.
_conn_conn = self.
_cache_cache.switch(index_or_alias)
487 NEW_ENVIRON_IS = b
'\x00'
488 NEW_ENVIRON_VAR = b
'\x00'
489 NEW_ENVIRON_VALUE = b
'\x01'
490 INTERNAL_UPDATE_FREQUENCY = 0.03
492 def __init__(self, host=None, port=23, timeout=3.0, newline='CRLF',
493 prompt=None, prompt_is_regexp=False,
494 encoding='UTF-8', encoding_errors='ignore',
495 default_log_level='INFO', window_size=None, environ_user=None,
496 terminal_emulation=False, terminal_type=None,
497 telnetlib_log_level='TRACE', connection_timeout=None):
498 if connection_timeout
is None:
499 telnetlib.Telnet.__init__(self, host, int(port)
if port
else 23)
501 telnetlib.Telnet.__init__(self, host, int(port)
if port
else 23,
505 self.
_set_prompt_set_prompt(prompt, prompt_is_regexp)
556 raise AssertionError(
"Newline can not be changed when terminal emulation is used.")
562 newline = str(newline).upper()
563 self.
_newline_newline = newline.replace(
'LF',
'\n').replace(
'CR',
'\r')
588 self.
_set_prompt_set_prompt(prompt, prompt_is_regexp)
590 return old[0].pattern,
True
595 self.
_prompt_prompt = (re.compile(prompt),
True)
597 self.
_prompt_prompt = (prompt,
False)
600 return self.
_prompt_prompt[0]
is not None
624 raise AssertionError(
"Encoding can not be changed when terminal emulation is used.")
626 self.
_set_encoding_set_encoding(encoding
or old[0], errors
or old[1])
636 return text.encode(
'ASCII')
637 return text.encode(*self.
_encoding_encoding)
642 return bytes.decode(*self.
_encoding_encoding)
656 if level.upper() ==
'NONE':
686 return level.upper()
in (
'TRACE',
'DEBUG',
'INFO',
'WARN')
700 self.sock.shutdown(socket.SHUT_RDWR)
702 output = self.
_decode_decode(self.read_all())
703 self.
_log_log(output, loglevel)
730 def login(self, username, password, login_prompt='login:
',
731 password_prompt='Password: ', login_timeout=
'1 second',
732 login_incorrect=
'Login incorrect'):
739 login_timeout, login_incorrect)
741 self.
_log_log(output)
749 output = self.
read_untilread_until(login_prompt,
'TRACE')
751 output += self.
read_untilread_until(password_prompt,
'TRACE')
757 output = self.
readread(
'TRACE')
758 success = incorrect
not in output
759 return success, output
777 def write(self, text, loglevel=None):
780 raise RuntimeError(
"'Write' keyword cannot be used with strings "
781 "containing newlines. Use 'Write Bare' instead.")
798 telnetlib.Telnet.write(self, self.
_encode_encode(text))
823 retry_interval, loglevel=None):
826 maxtime = time.time() + timeout
827 while time.time() < maxtime:
832 return self.
read_untilread_until(expected, loglevel)
833 except AssertionError:
856 ordinal = int(int_or_name)
857 return bytes(bytearray([ordinal]))
863 'BRK' : telnetlib.BRK,
866 'AYT' : telnetlib.AYT,
869 'NOP' : telnetlib.NOP
872 return code_names[name]
874 raise RuntimeError(
"Unsupported control character '%s'." % name)
883 output = self.
_decode_decode(self.read_very_eager())
887 self.
_log_log(output, loglevel)
900 success, output = self.
_read_until_read_until(expected)
901 self.
_log_log(output, loglevel)
910 expected = self.
_encode_encode(expected)
911 output = telnetlib.Telnet.read_until(self, expected, self.
_timeout_timeout)
912 return output.endswith(expected), self.
_decode_decode(output)
915 _terminal_frequency = property
921 max_time = time.time() + self.
_timeout_timeout
925 while time.time() < max_time:
926 output = telnetlib.Telnet.read_until(self, self.
_encode_encode(expected),
943 max_time = time.time() + self.
_timeout_timeout
944 regexps_bytes = [self.
_to_byte_regexp_to_byte_regexp(rgx)
for rgx
in expected_list]
945 regexps_unicode = [re.compile(self.
_decode_decode(rgx.pattern))
946 for rgx
in regexps_bytes]
950 while time.time() < max_time:
959 expected = [self.
_to_byte_regexp_to_byte_regexp(exp)
for exp
in expected_list]
961 index, _, output = self.expect(expected, self.
_timeout_timeout)
963 index, output = -1, b
''
964 return index != -1, self.
_decode_decode(output)
968 return re.compile(exp)
970 return re.compile(self.
_encode_encode(exp))
971 pattern = exp.pattern
974 return re.compile(self.
_encode_encode(pattern))
1001 loglevel = expected[-1]
1002 expected = expected[:-1]
1006 self.
_log_log(output, loglevel)
1008 expected = [exp
if is_string(exp)
else exp.pattern
1009 for exp
in expected]
1034 self.
_log_log(output, loglevel)
1036 prompt, regexp = self.
_prompt_prompt
1038 % (prompt
if not regexp
else prompt.pattern,
1045 prompt, regexp = self.
_prompt_prompt
1050 prompt, regexp = self.
_prompt_prompt
1052 length = len(prompt)
1054 match = prompt.search(output)
1055 length = match.end() - match.start()
1056 return output[:-length]
1075 self.
writewrite(command, loglevel)
1099 if cmd
in (telnetlib.DO, telnetlib.DONT, telnetlib.WILL, telnetlib.WONT):
1106 if opt == telnetlib.ECHO
and cmd
in (telnetlib.WILL, telnetlib.WONT):
1108 elif cmd == telnetlib.DO
and opt == telnetlib.TTYPE
and self.
_terminal_type_terminal_type:
1110 elif cmd == telnetlib.DO
and opt == telnetlib.NEW_ENVIRON
and self.
_environ_user_environ_user:
1112 elif cmd == telnetlib.DO
and opt == telnetlib.NAWS
and self.
_window_size_window_size:
1114 elif opt != telnetlib.NOOPT:
1118 return self.sock.sendall(telnetlib.IAC + telnetlib.DO + opt)
1121 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1122 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.TTYPE
1124 + telnetlib.IAC + telnetlib.SE)
1127 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1128 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NEW_ENVIRON
1131 + telnetlib.IAC + telnetlib.SE)
1134 self.sock.sendall(telnetlib.IAC + telnetlib.WILL + opt)
1135 self.sock.sendall(telnetlib.IAC + telnetlib.SB + telnetlib.NAWS
1136 + struct.pack(
'!HH', window_x, window_y)
1137 + telnetlib.IAC + telnetlib.SE)
1140 if cmd
in (telnetlib.DO, telnetlib.DONT):
1141 self.sock.sendall(telnetlib.IAC + telnetlib.WONT + opt)
1142 elif cmd
in (telnetlib.WILL, telnetlib.WONT):
1143 self.sock.sendall(telnetlib.IAC + telnetlib.DONT + opt)
1151 if not terminal_emulation:
1154 raise RuntimeError(
"Terminal emulation requires pyte module!\n"
1155 "http://pypi.python.org/pypi/pyte/")
1163 self._rows, self.
_columns_columns = window_size
or (200, 200)
1166 self.
_screen_screen = pyte.HistoryScreen(self._rows,
1174 current_output = property
1185 if not screen.history.top:
1188 for row
in screen.history.top:
1190 data = (char.data
for _, char
in sorted(row.items()))
1191 rows.append(
''.join(data).rstrip())
1195 rows = (row.rstrip()
for row
in screen.display)
1209 exp_index = current_out.find(expected)
1211 self.
_update_buffer_update_buffer(current_out[exp_index+len(expected):])
1212 return current_out[:exp_index+len(expected)]
1217 for rgx
in regexp_list:
1218 match = rgx.search(current_out)
1221 return current_out[:match.end()]
1225 self.
_buffer_buffer = terminal_buffer
1231 ROBOT_SUPPRESS_NAME =
True
1237 AssertionError.__init__(self, self.
_get_message_get_message())
1240 expected =
"'%s'" % self.
expectedexpected \
1243 msg =
"No match found for %s in %s." % (expected, self.
timeouttimeout)
1244 if self.
outputoutput
is not None:
1245 msg +=
' Output:\n%s' % self.
outputoutput
def __init__(self, expected, timeout, output=None)
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 _set_telnetlib_log_level(self, level)
def _set_encoding(self, encoding, errors)
def write_control_character(self, character)
Writes the given control character into the connection.
def read_until_regexp(self, *expected)
Reads output until any of the expected regular expressions match.
def _set_prompt(self, prompt, prompt_is_regexp)
def _custom_timeout(self, timeout)
def _verify_connection(self)
def _terminal_read_until(self, expected)
def _verify_login_without_prompt(self, delay, incorrect)
def set_encoding(self, encoding=None, errors=None)
Sets the encoding to use for writing and reading in the current connection.
def _opt_environ_user(self, opt, environ_user)
def _read_until(self, expected)
def _opt_echo_on(self, opt)
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 _get_newline_for(self, text)
def set_telnetlib_log_level(self, level)
Sets the log level used for logging in the underlying telnetlib.
def _terminal_frequency(self)
def _set_default_log_level(self, level)
def read(self, loglevel=None)
Reads everything that is currently available in the output.
def _read_until_prompt(self)
def msg(self, msg, *args)
def _opt_terminal_type(self, opt, terminal_type)
def _get_control_character(self, int_or_name)
def close_connection(self, loglevel=None)
Closes the current Telnet connection.
def _convert_control_code_name_to_character(self, name)
def read_until(self, expected, loglevel=None)
Reads output until expected text is encountered.
def _opt_dont_and_wont(self, cmd, opt)
def _log(self, msg, level=None)
def _is_valid_log_level(self, level)
float INTERNAL_UPDATE_FREQUENCY
def _opt_window_size(self, opt, window_x, window_y)
def _telnet_read_until_regexp(self, expected_list)
def _check_terminal_emulation(self, terminal_emulation)
def write_bare(self, text)
Writes the given text, and nothing else, into the connection.
def _read_until_regexp(self, *expected)
def set_default_log_level(self, level)
Sets the default log level used for logging in the current connection.
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 set_timeout(self, timeout)
Sets the timeout used for waiting output in the current connection.
def _set_timeout(self, timeout)
def set_newline(self, newline)
Sets the newline used by Write keyword 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 read_until_prompt(self, loglevel=None, strip_prompt=False)
Reads output until the prompt is encountered.
def _negotiate_options(self, sock, cmd, opt)
def write(self, text, loglevel=None)
Writes the given text plus a newline into the connection.
def _submit_credentials(self, username, password, login_prompt, password_prompt)
def _set_newline(self, newline)
def _terminal_read_until_regexp(self, expected_list)
def _to_byte_regexp(self, exp)
def _strip_prompt(self, output)
def execute_command(self, command, loglevel=None, strip_prompt=False)
Executes the given command and reads, logs, and returns everything until the prompt.
A library providing communication over Telnet connections.
def get_keyword_names(self)
def close_all_connections(self)
Closes all open connections and empties the connection cache.
def _get_library_keywords(self)
def _get_connection_keywords(self)
def _get_keywords(self, source, excluded)
def _parse_window_size(self, window_size)
def _set_connection_timeout(self, connection_timeout)
def __getattr__(self, name)
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 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 _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 _is_keyword(self, name, source, excluded)
def _get_screen(self, screen)
def _get_history(self, screen)
def __init__(self, window_size=None, newline="\r\n")
def read_until(self, expected)
def _update_buffer(self, terminal_buffer)
_whitespace_after_last_feed
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, accept_plain_values=True)
Parses time strings like '1h 10s', '01:00:10' and '42' and returns seconds.
def is_truthy(item)
Returns True or False depending on is the item considered true or not.
def get_version(naked=False)