1:mod:`telnetlib` --- Telnet client
2==================================
3
4.. module:: telnetlib
5   :synopsis: Telnet client class.
6   :deprecated:
7
8.. sectionauthor:: Skip Montanaro <[email protected]>
9
10**Source code:** :source:`Lib/telnetlib.py`
11
12.. index:: single: protocol; Telnet
13
14.. deprecated-removed:: 3.11 3.13
15   The :mod:`telnetlib` module is deprecated
16   (see :pep:`PEP 594 <594#telnetlib>` for details and alternatives).
17
18--------------
19
20The :mod:`telnetlib` module provides a :class:`Telnet` class that implements the
21Telnet protocol.  See :rfc:`854` for details about the protocol. In addition, it
22provides symbolic constants for the protocol characters (see below), and for the
23telnet options. The symbolic names of the telnet options follow the definitions
24in ``arpa/telnet.h``, with the leading ``TELOPT_`` removed. For symbolic names
25of options which are traditionally not included in ``arpa/telnet.h``, see the
26module source itself.
27
28The symbolic constants for the telnet commands are: IAC, DONT, DO, WONT, WILL,
29SE (Subnegotiation End), NOP (No Operation), DM (Data Mark), BRK (Break), IP
30(Interrupt process), AO (Abort output), AYT (Are You There), EC (Erase
31Character), EL (Erase Line), GA (Go Ahead), SB (Subnegotiation Begin).
32
33.. include:: ../includes/wasm-notavail.rst
34
35.. class:: Telnet(host=None, port=0[, timeout])
36
37   :class:`Telnet` represents a connection to a Telnet server. The instance is
38   initially not connected by default; the :meth:`~Telnet.open` method must be used to
39   establish a connection.  Alternatively, the host name and optional port
40   number can be passed to the constructor too, in which case the connection to
41   the server will be established before the constructor returns.  The optional
42   *timeout* parameter specifies a timeout in seconds for blocking operations
43   like the connection attempt (if not specified, the global default timeout
44   setting will be used).
45
46   Do not reopen an already connected instance.
47
48   This class has many :meth:`read_\*` methods.  Note that some of them  raise
49   :exc:`EOFError` when the end of the connection is read, because they can return
50   an empty string for other reasons.  See the individual descriptions below.
51
52   A :class:`Telnet` object is a context manager and can be used in a
53   :keyword:`with` statement.  When the :keyword:`!with` block ends, the
54   :meth:`close` method is called::
55
56       >>> from telnetlib import Telnet
57       >>> with Telnet('localhost', 23) as tn:
58       ...     tn.interact()
59       ...
60
61   .. versionchanged:: 3.6 Context manager support added
62
63
64.. seealso::
65
66   :rfc:`854` - Telnet Protocol Specification
67      Definition of the Telnet protocol.
68
69
70.. _telnet-objects:
71
72Telnet Objects
73--------------
74
75:class:`Telnet` instances have the following methods:
76
77
78.. method:: Telnet.read_until(expected, timeout=None)
79
80   Read until a given byte string, *expected*, is encountered or until *timeout*
81   seconds have passed.
82
83   When no match is found, return whatever is available instead, possibly empty
84   bytes.  Raise :exc:`EOFError` if the connection is closed and no cooked data
85   is available.
86
87
88.. method:: Telnet.read_all()
89
90   Read all data until EOF as bytes; block until connection closed.
91
92
93.. method:: Telnet.read_some()
94
95   Read at least one byte of cooked data unless EOF is hit. Return ``b''`` if
96   EOF is hit.  Block if no data is immediately available.
97
98
99.. method:: Telnet.read_very_eager()
100
101   Read everything that can be without blocking in I/O (eager).
102
103   Raise :exc:`EOFError` if connection closed and no cooked data available.
104   Return ``b''`` if no cooked data available otherwise. Do not block unless in
105   the midst of an IAC sequence.
106
107
108.. method:: Telnet.read_eager()
109
110   Read readily available data.
111
112   Raise :exc:`EOFError` if connection closed and no cooked data available.
113   Return ``b''`` if no cooked data available otherwise. Do not block unless in
114   the midst of an IAC sequence.
115
116
117.. method:: Telnet.read_lazy()
118
119   Process and return data already in the queues (lazy).
120
121   Raise :exc:`EOFError` if connection closed and no data available. Return
122   ``b''`` if no cooked data available otherwise.  Do not block unless in the
123   midst of an IAC sequence.
124
125
126.. method:: Telnet.read_very_lazy()
127
128   Return any data available in the cooked queue (very lazy).
129
130   Raise :exc:`EOFError` if connection closed and no data available. Return
131   ``b''`` if no cooked data available otherwise.  This method never blocks.
132
133
134.. method:: Telnet.read_sb_data()
135
136   Return the data collected between a SB/SE pair (suboption begin/end). The
137   callback should access these data when it was invoked with a ``SE`` command.
138   This method never blocks.
139
140
141.. method:: Telnet.open(host, port=0[, timeout])
142
143   Connect to a host. The optional second argument is the port number, which
144   defaults to the standard Telnet port (23). The optional *timeout* parameter
145   specifies a timeout in seconds for blocking operations like the connection
146   attempt (if not specified, the global default timeout setting will be used).
147
148   Do not try to reopen an already connected instance.
149
150   .. audit-event:: telnetlib.Telnet.open self,host,port telnetlib.Telnet.open
151
152
153.. method:: Telnet.msg(msg, *args)
154
155   Print a debug message when the debug level is ``>`` 0. If extra arguments are
156   present, they are substituted in the message using the standard string
157   formatting operator.
158
159
160.. method:: Telnet.set_debuglevel(debuglevel)
161
162   Set the debug level.  The higher the value of *debuglevel*, the more debug
163   output you get (on ``sys.stdout``).
164
165
166.. method:: Telnet.close()
167
168   Close the connection.
169
170
171.. method:: Telnet.get_socket()
172
173   Return the socket object used internally.
174
175
176.. method:: Telnet.fileno()
177
178   Return the file descriptor of the socket object used internally.
179
180
181.. method:: Telnet.write(buffer)
182
183   Write a byte string to the socket, doubling any IAC characters. This can
184   block if the connection is blocked.  May raise :exc:`OSError` if the
185   connection is closed.
186
187   .. audit-event:: telnetlib.Telnet.write self,buffer telnetlib.Telnet.write
188
189   .. versionchanged:: 3.3
190      This method used to raise :exc:`socket.error`, which is now an alias
191      of :exc:`OSError`.
192
193
194.. method:: Telnet.interact()
195
196   Interaction function, emulates a very dumb Telnet client.
197
198
199.. method:: Telnet.mt_interact()
200
201   Multithreaded version of :meth:`interact`.
202
203
204.. method:: Telnet.expect(list, timeout=None)
205
206   Read until one from a list of a regular expressions matches.
207
208   The first argument is a list of regular expressions, either compiled
209   (:ref:`regex objects <re-objects>`) or uncompiled (byte strings). The
210   optional second argument is a timeout, in seconds; the default is to block
211   indefinitely.
212
213   Return a tuple of three items: the index in the list of the first regular
214   expression that matches; the match object returned; and the bytes read up
215   till and including the match.
216
217   If end of file is found and no bytes were read, raise :exc:`EOFError`.
218   Otherwise, when nothing matches, return ``(-1, None, data)`` where *data* is
219   the bytes received so far (may be empty bytes if a timeout happened).
220
221   If a regular expression ends with a greedy match (such as ``.*``) or if more
222   than one expression can match the same input, the results are
223   non-deterministic, and may depend on the I/O timing.
224
225
226.. method:: Telnet.set_option_negotiation_callback(callback)
227
228   Each time a telnet option is read on the input flow, this *callback* (if set) is
229   called with the following parameters: callback(telnet socket, command
230   (DO/DONT/WILL/WONT), option).  No other action is done afterwards by telnetlib.
231
232
233.. _telnet-example:
234
235Telnet Example
236--------------
237
238.. sectionauthor:: Peter Funk <[email protected]>
239
240
241A simple example illustrating typical use::
242
243   import getpass
244   import telnetlib
245
246   HOST = "localhost"
247   user = input("Enter your remote account: ")
248   password = getpass.getpass()
249
250   tn = telnetlib.Telnet(HOST)
251
252   tn.read_until(b"login: ")
253   tn.write(user.encode('ascii') + b"\n")
254   if password:
255       tn.read_until(b"Password: ")
256       tn.write(password.encode('ascii') + b"\n")
257
258   tn.write(b"ls\n")
259   tn.write(b"exit\n")
260
261   print(tn.read_all().decode('ascii'))
262
263