stream_writer¶
Module provides TelnetWriter
and TelnetWriterUnicode
.
-
class
TelnetWriter
(transport, protocol, *, client=False, server=False, reader=None, loop=None, log=None)[source]¶ A writer interface for the telnet protocol.
Telnet IAC Interpreter.
Almost all negotiation actions are performed through the writer interface, as any action requires writing bytes to the underling stream. This class implements
feed_byte()
, which acts as a Telnet Is-A-Command (IAC) interpreter.The significance of the last byte passed to this method is tested by instance attribute
is_oob
, following the call tofeed_byte()
to determine whether the given byte is in or out of band.A minimal Telnet Protocol method,
asyncio.Protocol.data_received()
, should forward each byte tofeed_byte()
, which returns True to indicate the given byte should be forwarded to a Protocol reader method.- Parameters
client¶ (bool) – Whether the IAC interpreter should react from the client point of view.
server¶ (bool) – Whether the IAC interpreter should react from the server point of view.
log¶ (logging.Logger) – target logger, if None is given, one is created using the namespace
'telnetlib3.stream_writer'
.loop¶ (asyncio.AbstractEventLoop) – set the event loop to use. The return value of
asyncio.get_event_loop()
is used when unset.
-
byte_count
= 0¶ Total bytes sent to
feed_byte()
-
lflow
= True¶ Whether flow control is enabled.
-
xon_any
= False¶ Whether flow control enabled by Transmit-Off (XOFF) (Ctrl-s), should re-enable Transmit-On (XON) only on receipt of XON (Ctrl-q). When False, any keypress from client re-enables transmission.
-
iac_received
= None¶ Whether the last byte received by
feed_byte()
is the beginning of an IAC command.
-
cmd_received
= None¶ Whether the last byte received by
feed_byte()
begins an IAC command sequence.
-
slc_received
= None¶ Whether the last byte received by
feed_byte()
is a matching special line character value, if negotiated.
-
slc_simulated
= True¶ SLC function values and callbacks are fired for clients in Kludge mode not otherwise capable of negotiating LINEMODE, providing transport remote editing function callbacks for dumb clients.
-
default_linemode
= <b'\x10': lit_echo:True, soft_tab:False, ack:False, trapsig:False, remote:True, local:False>¶ Initial line mode requested by server if client supports LINEMODE negotiation (remote line editing and literal echo of control chars)
-
pending_option
¶ Dictionary of telnet option byte(s) that follow an IAC-DO or IAC-DONT command, and contains a value of
True
until IAC-WILL or IAC-WONT has been received by remote end.
-
local_option
¶ Dictionary of telnet option byte(s) that follow an IAC-WILL or IAC-WONT command, sent by our end, indicating state of local capabilities.
-
remote_option
¶ Dictionary of telnet option byte(s) that follow an IAC-WILL or IAC-WONT command received by remote end, indicating state of remote capabilities.
-
slctab
¶ SLC Tab (SLC Functions and their support level, and ascii value)
-
writelines
(lines)[source]¶ Write unicode strings to transport.
Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.
-
feed_byte
(byte)[source]¶ Feed a single byte into Telnet option state machine.
- Parameters
byte¶ (int) – an 8-bit byte value as integer (0-255), or a bytes array. When a bytes array, it must be of length 1.
- Rtype bool
Whether the given
byte
is “in band”, that is, should be duplicated to a connected terminal or device.False
is returned for anIAC
command for each byte until its completion.
-
property
protocol
¶ The protocol attached to this stream.
-
property
server
¶ Whether this stream is of the server’s point of view.
-
property
client
¶ Whether this stream is of the client’s point of view.
-
echo
(data)[source]¶ Conditionally write
data
to transport when “remote echo” enabled.The default implementation depends on telnet negotiation willingness for local echo, only an RFC-compliant telnet client will correctly set or unset echo accordingly by demand.
-
property
will_echo
¶ Whether Server end is expected to echo back input sent by client.
From server perspective: the server should echo (duplicate) client input back over the wire, the client is awaiting this data to indicate their input has been received.
From client perspective: the server will not echo our input, we should chose to duplicate our input to standard out ourselves.
-
property
mode
¶ String describing NVT mode.
- Rtype str
One of:
kludge
: Client acknowledges WILL-ECHO, WILL-SGA. character-at-a-time and remote line editing may be provided.
local
: Default NVT half-duplex mode, client performs lineediting and transmits only after pressing send (usually CR)
remote
: Client supports advanced remote line editing, usingmixed-mode local line buffering (optionally, echoing) until send, but also transmits buffer up to and including special line characters (SLCs).
-
property
is_oob
¶ The previous byte should not be received by the API stream.
-
property
linemode
¶ Linemode instance for stream.
Note
value is meaningful after successful LINEMODE negotiation, otherwise does not represent the linemode state of the stream.
Attributes of the stream’s active linemode may be tested using boolean instance attributes,
edit
,trapsig
,soft_tab
,lit_echo
,remote
,local
.
-
send_iac
(buf)[source]¶ Send a command starting with IAC (base 10 byte value 255).
No transformations of bytes are performed. Normally, if the byte value 255 is sent, it is escaped as
IAC + IAC
. This method ensures it is not escaped,.
-
iac
(cmd, opt=b'')[source]¶ Send Is-A-Command 3-byte negotiation command.
Returns True if command was sent. Not all commands are legal in the context of client, server, or pending negotiation state, emitting a relevant debug warning to the log handler if not sent.
-
send_ga
()[source]¶ Transmit IAC GA (Go-Ahead).
Returns True if sent. If IAC-DO-SGA has been received, then False is returned and IAC-GA is not transmitted.
-
send_eor
()[source]¶ Transmit IAC CMD_EOR (End-of-Record), RFC 885.
Returns True if sent. If IAC-DO-EOR has not been received, False is returned and IAC-CMD_EOR is not transmitted.
-
request_status
()[source]¶ Send
IAC-SB-STATUS-SEND
sub-negotiation (RFC 859).This method may only be called after
IAC-WILL-STATUS
has been received. Returns True if status request was sent.
-
request_tspeed
()[source]¶ Send IAC-SB-TSPEED-SEND sub-negotiation, RFC 1079.
This method may only be called after
IAC-WILL-TSPEED
has been received. Returns True if TSPEED request was sent.
-
request_charset
()[source]¶ Request sub-negotiation CHARSET, RFC 2066.
Returns True if request is valid for telnet state, and was sent.
The sender requests that all text sent to and by it be encoded in one of character sets specified by string list
codepages
, which is determined by function value returned by callback registered usingset_ext_send_callback()
with valueCHARSET
.
-
request_environ
()[source]¶ Request sub-negotiation NEW_ENVIRON, RFC 1572.
Returns True if request is valid for telnet state, and was sent.
-
request_xdisploc
()[source]¶ Send XDISPLOC, SEND sub-negotiation, RFC 1086.
Returns True if request is valid for telnet state, and was sent.
-
request_ttype
()[source]¶ Send TTYPE SEND sub-negotiation, RFC 930.
Returns True if request is valid for telnet state, and was sent.
-
request_forwardmask
(fmask=None)[source]¶ Request the client forward their terminal control characters.
Characters are indicated in the
Forwardmask
instancefmask
. When fmask is None, a forwardmask is generated for the SLC characters registered byslctab
.
-
send_lineflow_mode
()[source]¶ Send LFLOW mode sub-negotiation, RFC 1372.
Returns True if request is valid for telnet state, and was sent.
-
send_linemode
(linemode=None)[source]¶ Set and Inform other end to agree to change to linemode,
linemode
.An instance of the Linemode class, or self.linemode when unset.
-
set_iac_callback
(cmd, func)[source]¶ Register callable
func
as callback for IACcmd
.BRK, IP, AO, AYT, EC, EL, CMD_EOR, EOF, SUSP, ABORT, and NOP.
These callbacks receive a single argument, the IAC
cmd
which triggered it.
-
handle_el
(byte)[source]¶ Handle IAC Erase Line (EL, SLC_EL).
Provides a function which discards all the data ready on current line of input. The prompt should be re-displayed.
-
handle_abort
(byte)[source]¶ Handle IAC Abort (ABORT, SLC_ABORT).
Similar to Interrupt Process (IP), but means only to abort or terminate the process to which the NVT is connected.
-
handle_susp
(byte)[source]¶ Handle IAC Suspend Process (SUSP, SLC_SUSP).
Suspends the execution of the current process attached to the NVT in such a way that another process will take over control of the NVT, and the suspended process can be resumed at a later time.
If the receiving system does not support this functionality, it should be ignored.
-
handle_brk
(byte)[source]¶ Handle IAC Break (BRK, SLC_BRK).
Sent by clients to indicate BREAK keypress. This is not the same as IP (^c), but a means to map sysystem-dependent break key such as found on an IBM Systems.
-
handle_ayt
(byte)[source]¶ Handle IAC Are You There (AYT, SLC_AYT).
Provides the user with some visible (e.g., printable) evidence that the system is still up and running.
-
handle_ao
(byte)[source]¶ Handle IAC Abort Output (AO) or SLC_AO.
Discards any remaining output on the transport buffer.
[…] a reasonable implementation would be to suppress the remainder of the text string, but transmit the prompt character and the preceding <CR><LF>.
-
handle_ec
(byte)[source]¶ Handle IAC Erase Character (EC, SLC_EC).
Provides a function which deletes the last preceding undeleted character from data ready on current line of input.
-
handle_tm
(cmd)[source]¶ Handle IAC (WILL, WONT, DO, DONT) Timing Mark (TM).
TM is essentially a NOP that any IAC interpreter must answer, if at least it answers WONT to unknown options (required), it may still be used as a means to accurately measure the “ping” time.
-
set_slc_callback
(slc_byte, func)[source]¶ Register
func
as callable for receipt ofslc_byte
.- Parameters
slc_byte¶ (bytes) – any of SLC_SYNCH, SLC_BRK, SLC_IP, SLC_AO, SLC_AYT, SLC_EOR, SLC_ABORT, SLC_EOF, SLC_SUSP, SLC_EC, SLC_EL, SLC_EW, SLC_RP, SLC_XON, SLC_XOFF …
func¶ (Callable) – These callbacks receive a single argument: the SLC function byte that fired it. Some SLC and IAC functions are intermixed; which signaling mechanism used by client can be tested by evaluating this argument.
-
handle_ew
(slc)[source]¶ Handle SLC_EW (Erase Word).
Provides a function which deletes the last preceding undeleted character, and any subsequent bytes until next whitespace character from data ready on current line of input.
-
set_ext_send_callback
(cmd, func)[source]¶ Register callback for inquires of sub-negotiation of
cmd
.- Parameters
func¶ (Callable) – A callable function for the given
cmd
byte. Note that the return type must match those documented.These callbacks must return any number of arguments, for each registered
cmd
byte, respectively:SNDLOC: for clients, returning one argument: the string describing client location, such as
b'ROOM 641-A'
, RFC 779.NAWS: for clients, returning two integer arguments (width, height), such as (80, 24), RFC 1073.
TSPEED: for clients, returning two integer arguments (rx, tx) such as (57600, 57600), RFC 1079.
TTYPE: for clients, returning one string, usually the terminfo(5) database capability name, such as ‘xterm’, RFC 1091.
XDISPLOC: for clients, returning one string, the DISPLAY host value, in form of <host>:<dispnum>[.<screennum>], RFC 1096.
NEW_ENVIRON: for clients, returning a dictionary of (key, val) pairs of environment item values, RFC 1408.
CHARSET: for clients, receiving iterable of strings of character sets requested by server, callback must return one of those strings given, RFC 2066.
-
set_ext_callback
(cmd, func)[source]¶ Register
func
as callback for receipt ofcmd
negotiation.LOGOUT
: for servers and clients, receiving one argument. Server end may receive DO or DONT as argumentcmd
, indicating client’s wish to disconnect, or a response to WILL, LOGOUT, indicating it’s wish not to be automatically disconnected. Client end may receive WILL or WONT, indicating server’s wish to disconnect, or acknowledgment that the client will not be disconnected.SNDLOC
: for servers, receiving one argument: the string describing the client location, such as'ROOM 641-A'
, RFC 779.NAWS
: for servers, receiving two integer arguments (width, height), such as (80, 24), RFC 1073.TSPEED
: for servers, receiving two integer arguments (rx, tx) such as (57600, 57600), RFC 1079.TTYPE
: for servers, receiving one string, usually the terminfo(5) database capability name, such as ‘xterm’, RFC 1091.XDISPLOC
: for servers, receiving one string, the DISPLAY host value, in form of<host>:<dispnum>[.<screennum>]
, RFC 1096.NEW_ENVIRON
: for servers, receiving a dictionary of(key, val)
pairs of remote client environment item values, RFC 1408.CHARSET
: for servers, receiving one string, the character set negotiated by client. RFC 2066.
-
handle_ttype
(ttype)[source]¶ Receive TTYPE value
ttype
, RFC 1091.A string value that represents client’s emulation capability.
Some example values: VT220, VT100, ANSITERM, ANSI, TTY, and 5250.
-
handle_send_client_environ
(keys)[source]¶ Send environment variables as dict, RFC 1572.
If argument
keys
is empty, then all available values should be sent. Otherwise,keys
is a set of environment keys explicitly requested.
-
handle_send_client_charset
(charsets)[source]¶ Send character set selection as string, RFC 2066.
Given the available encodings presented by the server, select and return only one. Returning an empty string indicates that no selection is made (request is ignored).
-
handle_send_server_charset
(charsets)[source]¶ Send character set (encodings) offered to client, RFC 2066.
-
handle_logout
(cmd)[source]¶ Handle (IAC, (DO | DONT | WILL | WONT), LOGOUT), RFC 727.
Only the server end may receive (DO, DONT). Only the client end may receive (WILL, WONT).
-
handle_do
(opt)[source]¶ Process byte 3 of series (IAC, DO, opt) received by remote end.
This method can be derived to change or extend protocol capabilities, for most cases, simply returning True if supported, False otherwise.
In special cases of various RFC statutes, state is stored and answered in willing affirmative, with the exception of:
DO TM is always answered WILL TM, even if it was already replied to. No state is stored (“Timing Mark”), and the IAC callback registered by
set_ext_callback()
for cmd TM is called with argument byteDO
.DO LOGOUT executes extended callback registered by cmd LOGOUT with argument DO (indicating a request for voluntary logoff).
DO STATUS sends state of all local, remote, and pending options.
-
handle_dont
(opt)[source]¶ Process byte 3 of series (IAC, DONT, opt) received by remote end.
This only results in
self.local_option[opt]
set toFalse
, with the exception of (IAC, DONT, LOGOUT), which only signals a callback tohandle_logout(DONT)
.
-
handle_will
(opt)[source]¶ Process byte 3 of series (IAC, DONT, opt) received by remote end.
The remote end requests we perform any number of capabilities. Most implementations require an answer in the affirmative with DO, unless DO has meaning specific for only client or server end, and dissenting with DONT.
WILL ECHO may only be received for clients, answered with DO. WILL NAWS may only be received for servers, answered with DO. BINARY and SGA are answered with DO. STATUS, NEW_ENVIRON, XDISPLOC, and TTYPE is answered with sub-negotiation SEND. The env variables requested in response to WILL NEW_ENVIRON is “SEND ANY”. All others are replied with DONT.
The result of a supported capability is a response of (IAC, DO, opt) and the setting of
self.remote_option[opt]
ofTrue
. For unsupported capabilities, RFC specifies a response of (IAC, DONT, opt). Similarly, setself.remote_option[opt]
toFalse
.
-
handle_wont
(opt)[source]¶ Process byte 3 of series (IAC, WONT, opt) received by remote end.
(IAC, WONT, opt) is a negative acknowledgment of (IAC, DO, opt) sent.
The remote end requests we do not perform a telnet capability.
It is not possible to decline a WONT.
T.remote_option[opt]
is set False to indicate the remote end’s refusal to performopt
.
-
class
TelnetWriterUnicode
(transport, protocol, fn_encoding, *, encoding_errors='strict', **kwds)[source]¶ A Unicode StreamWriter interface for Telnet protocol.
See ancestor class,
TelnetWriter
for details.Requires the
fn_encoding
callback, receiving mutually boolean keyword argumentoutgoing=True
to determine what encoding should be used to decode the value in the direction specified.The encoding may be conditionally negotiated by CHARSET, RFC 2066, or discovered by
LANG
environment variables by NEW_ENVIRON, RFC 1572.A writer interface for the telnet protocol.
Telnet IAC Interpreter.
Almost all negotiation actions are performed through the writer interface, as any action requires writing bytes to the underling stream. This class implements
feed_byte()
, which acts as a Telnet Is-A-Command (IAC) interpreter.The significance of the last byte passed to this method is tested by instance attribute
is_oob
, following the call tofeed_byte()
to determine whether the given byte is in or out of band.A minimal Telnet Protocol method,
asyncio.Protocol.data_received()
, should forward each byte tofeed_byte()
, which returns True to indicate the given byte should be forwarded to a Protocol reader method.- Parameters
client¶ (bool) – Whether the IAC interpreter should react from the client point of view.
server¶ (bool) – Whether the IAC interpreter should react from the server point of view.
log¶ (logging.Logger) – target logger, if None is given, one is created using the namespace
'telnetlib3.stream_writer'
.loop¶ (asyncio.AbstractEventLoop) – set the event loop to use. The return value of
asyncio.get_event_loop()
is used when unset.
-
encode
(string, errors)[source]¶ Encode
string
using protocol-preferred encoding.- Parameters
errors¶ (str) – same as meaning in
codecs.Codec.encode()
. When None, value ofencoding_errors
given to class initializer is used.errors¶ – same as meaning in
codecs.Codec.encode()
, whenNone
(default), value of class initializer keyword argument,encoding_errors
.
-
write
(string, errors=None)[source]¶ Write unicode string to transport, using protocol-preferred encoding.
- Parameters
string¶ (str) – unicode string text to write to endpoint using the protocol’s preferred encoding. When the protocol
encoding
keyword is explicitly set toFalse
, the given string should be only rawb'bytes'
.errors¶ (str) – same as meaning in
codecs.Codec.encode()
, whenNone
(default), value of class initializer keyword argument,encoding_errors
.
- Return type
-
writelines
(lines, errors=None)[source]¶ Write unicode strings to transport.
Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string.
-
echo
(string, errors=None)[source]¶ Conditionally write
string
to transport when “remote echo” enabled.- Parameters
string¶ (str) – string received as input, conditionally written.
errors¶ (str) – same as meaning in
codecs.Codec.encode()
.
This method may only be called from the server perspective. The default implementation depends on telnet negotiation willingness for local echo: only an RFC-compliant telnet client will correctly set or unset echo accordingly by demand.