blob: b0863b1cbd60344254992ba11aad25eb973e63b1 [file] [log] [blame]
Hye-Shik Change029da02005-09-07 07:40:05 +00001r"""TELNET client class.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +00002
3Based on RFC 854: TELNET Protocol Specification, by J. Postel and
4J. Reynolds
5
6Example:
7
8>>> from telnetlib import Telnet
9>>> tn = Telnet('www.python.org', 79) # connect to finger port
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000010>>> tn.write(b'guido\r\n')
Guido van Rossum7131f842007-02-09 20:13:25 +000011>>> print(tn.read_all())
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000012Login Name TTY Idle When Where
13guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
Tim Petersb90f89a2001-01-15 03:26:36 +000014
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000015>>>
16
17Note that read_all() won't read until eof -- it just reads some data
18-- but it guarantees to read at least one byte unless EOF is hit.
19
Charles-François Natali64590252013-10-21 14:02:12 +020020It is possible to pass a Telnet object to a selector in order to wait until
21more data is available. Note that in this case, read_eager() may return b''
22even if there was data on the socket, because the protocol negotiation may have
23eaten the data. This is why EOFError is needed in some cases to distinguish
24between "no data" and "connection closed" (since the socket also appears ready
25for reading when it is closed).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000026
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000027To do:
28- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000029- timeout should be intrinsic to the connection object instead of an
30 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000031
32"""
33
34
35# Imported modules
Guido van Rossumccb5ec61997-12-24 22:24:19 +000036import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000037import socket
Charles-François Natali64590252013-10-21 14:02:12 +020038import selectors
Victor Stinnerae586492014-09-02 23:18:25 +020039from time import monotonic as _time
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000040
Skip Montanaro40fc1602001-03-01 04:27:19 +000041__all__ = ["Telnet"]
42
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000043# Tunable parameters
44DEBUGLEVEL = 0
45
46# Telnet protocol defaults
47TELNET_PORT = 23
48
49# Telnet protocol characters (don't change)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000050IAC = bytes([255]) # "Interpret As Command"
51DONT = bytes([254])
52DO = bytes([253])
53WONT = bytes([252])
54WILL = bytes([251])
55theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000056
Jack Diederich1c8f38c2009-04-10 05:33:26 +000057SE = bytes([240]) # Subnegotiation End
58NOP = bytes([241]) # No Operation
59DM = bytes([242]) # Data Mark
60BRK = bytes([243]) # Break
61IP = bytes([244]) # Interrupt process
62AO = bytes([245]) # Abort output
63AYT = bytes([246]) # Are You There
64EC = bytes([247]) # Erase Character
65EL = bytes([248]) # Erase Line
66GA = bytes([249]) # Go Ahead
67SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000068
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000069
Martin v. Löwisb0162f92001-09-06 08:51:38 +000070# Telnet protocol options code (don't change)
71# These ones all come from arpa/telnet.h
Jack Diederich1c8f38c2009-04-10 05:33:26 +000072BINARY = bytes([0]) # 8-bit data path
73ECHO = bytes([1]) # echo
74RCP = bytes([2]) # prepare to reconnect
75SGA = bytes([3]) # suppress go ahead
76NAMS = bytes([4]) # approximate message size
77STATUS = bytes([5]) # give status
78TM = bytes([6]) # timing mark
79RCTE = bytes([7]) # remote controlled transmission and echo
80NAOL = bytes([8]) # negotiate about output line width
81NAOP = bytes([9]) # negotiate about output page size
82NAOCRD = bytes([10]) # negotiate about CR disposition
83NAOHTS = bytes([11]) # negotiate about horizontal tabstops
84NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
85NAOFFD = bytes([13]) # negotiate about formfeed disposition
86NAOVTS = bytes([14]) # negotiate about vertical tab stops
87NAOVTD = bytes([15]) # negotiate about vertical tab disposition
88NAOLFD = bytes([16]) # negotiate about output LF disposition
89XASCII = bytes([17]) # extended ascii character set
90LOGOUT = bytes([18]) # force logout
91BM = bytes([19]) # byte macro
92DET = bytes([20]) # data entry terminal
93SUPDUP = bytes([21]) # supdup protocol
94SUPDUPOUTPUT = bytes([22]) # supdup output
95SNDLOC = bytes([23]) # send location
96TTYPE = bytes([24]) # terminal type
97EOR = bytes([25]) # end or record
98TUID = bytes([26]) # TACACS user identification
99OUTMRK = bytes([27]) # output marking
100TTYLOC = bytes([28]) # terminal location number
101VT3270REGIME = bytes([29]) # 3270 regime
102X3PAD = bytes([30]) # X.3 PAD
103NAWS = bytes([31]) # window size
104TSPEED = bytes([32]) # terminal speed
105LFLOW = bytes([33]) # remote flow control
106LINEMODE = bytes([34]) # Linemode option
107XDISPLOC = bytes([35]) # X Display Location
108OLD_ENVIRON = bytes([36]) # Old - Environment variables
109AUTHENTICATION = bytes([37]) # Authenticate
110ENCRYPT = bytes([38]) # Encryption option
111NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000112# the following ones come from
113# http://www.iana.org/assignments/telnet-options
114# Unfortunately, that document does not assign identifiers
115# to all of them, so we are making them up
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000116TN3270E = bytes([40]) # TN3270E
117XAUTH = bytes([41]) # XAUTH
118CHARSET = bytes([42]) # CHARSET
119RSP = bytes([43]) # Telnet Remote Serial Port
120COM_PORT_OPTION = bytes([44]) # Com Port Control Option
121SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
122TLS = bytes([46]) # Telnet Start TLS
123KERMIT = bytes([47]) # KERMIT
124SEND_URL = bytes([48]) # SEND-URL
125FORWARD_X = bytes([49]) # FORWARD_X
126PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
127SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
128PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
129EXOPL = bytes([255]) # Extended-Options-List
130NOOPT = bytes([0])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000131
Charles-François Natali64590252013-10-21 14:02:12 +0200132
133# poll/select have the advantage of not requiring any extra file descriptor,
134# contrarily to epoll/kqueue (also, they require a single syscall).
135if hasattr(selectors, 'PollSelector'):
136 _TelnetSelector = selectors.PollSelector
137else:
138 _TelnetSelector = selectors.SelectSelector
139
140
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000141class Telnet:
142
143 """Telnet interface class.
144
145 An instance of this class represents a connection to a telnet
146 server. The instance is initially not connected; the open()
147 method must be used to establish a connection. Alternatively, the
148 host name and optional port number can be passed to the
149 constructor, too.
150
151 Don't try to reopen an already connected instance.
152
153 This class has many read_*() methods. Note that some of them
154 raise EOFError when the end of the connection is read, because
155 they can return an empty string for other reasons. See the
156 individual doc strings.
157
158 read_until(expected, [timeout])
159 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000160 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000161
162 read_all()
163 Read all data until EOF; may block.
164
165 read_some()
166 Read at least one byte or EOF; may block.
167
168 read_very_eager()
169 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000171
172 read_eager()
173 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000175
176 read_lazy()
177 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000179
180 read_very_lazy()
181 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000183
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000184 read_sb_data()
185 Reads available data between SB ... SE sequence. Don't block.
186
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000187 set_option_negotiation_callback(callback)
188 Each time a telnet option is read on the input flow, this callback
189 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000190 callback(telnet socket, command, option)
191 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000192 No other action is done afterwards by telnetlib.
193
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000194 """
195
Georg Brandlf78e02b2008-06-10 17:40:04 +0000196 def __init__(self, host=None, port=0,
197 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000199
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000201 With a hostname argument, it connects the instance; port number
202 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 """
204 self.debuglevel = DEBUGLEVEL
205 self.host = host
206 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000207 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000209 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000210 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000211 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000213 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000214 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000215 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000216 self.option_callback = None
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000217 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000218 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000219
Georg Brandlf78e02b2008-06-10 17:40:04 +0000220 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000222
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 The optional second argument is the port number, which
224 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000225
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 Don't try to reopen an already connected instance.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 """
228 self.eof = 0
229 if not port:
230 port = TELNET_PORT
231 self.host = host
232 self.port = port
Georg Brandlf78e02b2008-06-10 17:40:04 +0000233 self.timeout = timeout
234 self.sock = socket.create_connection((host, port), timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000235
236 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 """Destructor -- close the connection."""
238 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000239
240 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000242
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 If extra arguments are present, they are substituted in the
244 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000245
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 """
247 if self.debuglevel > 0:
R. David Murray32ef70c2010-12-14 14:16:20 +0000248 print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000249 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000250 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000252 print(msg)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000253
254 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000255 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000256
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000257 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000258
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000259 """
260 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000261
262 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 """Close the connection."""
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300264 sock = self.sock
Serhiy Storchaka2116b122015-04-10 13:29:28 +0300265 self.sock = None
266 self.eof = True
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000267 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000268 self.sb = 0
Serhiy Storchaka7e7a3db2015-04-10 13:24:41 +0300269 if sock:
270 sock.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000271
272 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 """Return the socket object used internally."""
274 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000275
276 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 """Return the fileno() of the socket object used internally."""
278 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000279
280 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000281 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000282
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 Can block if the connection is blocked. May raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200284 OSError if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000285
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000286 """
287 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000288 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000289 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000290 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000291
292 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000293 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000294
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 When no match is found, return whatever is available instead,
296 possibly the empty string. Raise EOFError if the connection
297 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000298
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000299 """
300 n = len(match)
301 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000302 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000303 if i >= 0:
304 i = i+n
305 buf = self.cookedq[:i]
306 self.cookedq = self.cookedq[i:]
307 return buf
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200309 deadline = _time() + timeout
Charles-François Natali64590252013-10-21 14:02:12 +0200310 with _TelnetSelector() as selector:
311 selector.register(self, selectors.EVENT_READ)
312 while not self.eof:
313 if selector.select(timeout):
314 i = max(0, len(self.cookedq)-n)
315 self.fill_rawq()
316 self.process_rawq()
317 i = self.cookedq.find(match, i)
318 if i >= 0:
319 i = i+n
320 buf = self.cookedq[:i]
321 self.cookedq = self.cookedq[i:]
322 return buf
323 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200324 timeout = deadline - _time()
Charles-François Natali64590252013-10-21 14:02:12 +0200325 if timeout < 0:
326 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000327 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000328
329 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000330 """Read all data until EOF; block until connection closed."""
331 self.process_rawq()
332 while not self.eof:
333 self.fill_rawq()
334 self.process_rawq()
335 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000336 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000337 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000338
339 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000340 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000341
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000342 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000343 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000344
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000345 """
346 self.process_rawq()
347 while not self.cookedq and not self.eof:
348 self.fill_rawq()
349 self.process_rawq()
350 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000351 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000352 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000353
354 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000355 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000356
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000358 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000360
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 """
362 self.process_rawq()
363 while not self.eof and self.sock_avail():
364 self.fill_rawq()
365 self.process_rawq()
366 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000367
368 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000369 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000370
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000371 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000372 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000373 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000374
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000375 """
376 self.process_rawq()
377 while not self.cookedq and not self.eof and self.sock_avail():
378 self.fill_rawq()
379 self.process_rawq()
380 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000381
382 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000383 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000384
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000385 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000386 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000388
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 """
390 self.process_rawq()
391 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000392
393 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000395
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000397 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000398
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000399 """
400 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000401 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000402 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000403 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000404 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000405
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000406 def read_sb_data(self):
407 """Return any data available in the SB ... SE queue.
408
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000409 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000410 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000411 found, old unread SB data will be discarded. Don't block.
412
413 """
414 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000415 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000416 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000417
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000418 def set_option_negotiation_callback(self, callback):
419 """Provide a callback function called after each receipt of a telnet option."""
420 self.option_callback = callback
421
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000422 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000424
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 Set self.eof when connection is closed. Don't block unless in
426 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000427
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000428 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000429 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 try:
431 while self.rawq:
432 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000433 if not self.iacseq:
434 if c == theNULL:
435 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000436 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000437 continue
438 if c != IAC:
439 buf[self.sb] = buf[self.sb] + c
440 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000441 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000442 self.iacseq += c
443 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000444 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000445 if c in (DO, DONT, WILL, WONT):
446 self.iacseq += c
447 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000448
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000449 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000450 if c == IAC:
451 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000452 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000453 if c == SB: # SB ... SE start.
454 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000455 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000456 elif c == SE:
457 self.sb = 0
458 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000459 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000460 if self.option_callback:
461 # Callback is supposed to look into
462 # the sbdataq
463 self.option_callback(self.sock, c, NOOPT)
464 else:
465 # We can't offer automatic processing of
466 # suboptions. Alas, we should not get any
467 # unless we did a WILL/DO before.
468 self.msg('IAC %d not recognized' % ord(c))
469 elif len(self.iacseq) == 2:
Jack Diederich36596a32009-07-26 22:23:04 +0000470 cmd = self.iacseq[1:2]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000471 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000472 opt = c
473 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000474 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000475 cmd == DO and 'DO' or 'DONT', ord(opt))
476 if self.option_callback:
477 self.option_callback(self.sock, cmd, opt)
478 else:
479 self.sock.sendall(IAC + WONT + opt)
480 elif cmd in (WILL, WONT):
481 self.msg('IAC %s %d',
482 cmd == WILL and 'WILL' or 'WONT', ord(opt))
483 if self.option_callback:
484 self.option_callback(self.sock, cmd, opt)
485 else:
486 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000488 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000489 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000490 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000491 self.cookedq = self.cookedq + buf[0]
492 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000493
494 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000495 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000496
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000497 Block if no data is immediately available. Raise EOFError
498 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000499
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000500 """
501 if not self.rawq:
502 self.fill_rawq()
503 if self.eof:
504 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000505 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000506 self.irawq = self.irawq + 1
507 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000508 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000509 self.irawq = 0
510 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000511
512 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000513 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000514
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000515 Block if no data is immediately available. Set self.eof when
516 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000517
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000518 """
519 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000520 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000521 self.irawq = 0
522 # The buffer size should be fairly small so as to avoid quadratic
523 # behavior in process_rawq() above
524 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000525 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000526 self.eof = (not buf)
527 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000528
529 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000530 """Test whether data is available on the socket."""
Charles-François Natali64590252013-10-21 14:02:12 +0200531 with _TelnetSelector() as selector:
532 selector.register(self, selectors.EVENT_READ)
533 return bool(selector.select(0))
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000534
535 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000536 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000537 if sys.platform == "win32":
538 self.mt_interact()
539 return
Charles-François Natali64590252013-10-21 14:02:12 +0200540 with _TelnetSelector() as selector:
541 selector.register(self, selectors.EVENT_READ)
542 selector.register(sys.stdin, selectors.EVENT_READ)
543
544 while True:
545 for key, events in selector.select():
546 if key.fileobj is self:
547 try:
548 text = self.read_eager()
549 except EOFError:
550 print('*** Connection closed by remote host ***')
551 return
552 if text:
553 sys.stdout.write(text.decode('ascii'))
554 sys.stdout.flush()
555 elif key.fileobj is sys.stdin:
556 line = sys.stdin.readline().encode('ascii')
557 if not line:
558 return
559 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000560
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000561 def mt_interact(self):
562 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000563 import _thread
564 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000565 while 1:
566 line = sys.stdin.readline()
567 if not line:
568 break
R. David Murrayba488d12010-10-26 12:42:24 +0000569 self.write(line.encode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000570
571 def listener(self):
572 """Helper for mt_interact() -- this executes in the other thread."""
573 while 1:
574 try:
575 data = self.read_eager()
576 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000577 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000578 return
579 if data:
R. David Murrayba488d12010-10-26 12:42:24 +0000580 sys.stdout.write(data.decode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000581 else:
582 sys.stdout.flush()
583
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000584 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000585 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000586
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 The first argument is a list of regular expressions, either
588 compiled (re.RegexObject instances) or uncompiled (strings).
589 The optional second argument is a timeout, in seconds; default
590 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000591
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000592 Return a tuple of three items: the index in the list of the
593 first regular expression that matches; the match object
594 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000595
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000596 If EOF is read and no text was read, raise EOFError.
597 Otherwise, when nothing matches, return (-1, None, text) where
598 text is the text received so far (may be the empty string if a
599 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000600
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000601 If a regular expression ends with a greedy match (e.g. '.*')
602 or if more than one expression can match the same input, the
603 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000604
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000605 """
606 re = None
607 list = list[:]
608 indices = range(len(list))
609 for i in indices:
610 if not hasattr(list[i], "search"):
611 if not re: import re
612 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000613 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200614 deadline = _time() + timeout
Charles-François Natali64590252013-10-21 14:02:12 +0200615 with _TelnetSelector() as selector:
616 selector.register(self, selectors.EVENT_READ)
617 while not self.eof:
618 self.process_rawq()
619 for i in indices:
620 m = list[i].search(self.cookedq)
621 if m:
622 e = m.end()
623 text = self.cookedq[:e]
624 self.cookedq = self.cookedq[e:]
625 return (i, m, text)
626 if timeout is not None:
627 ready = selector.select(timeout)
Victor Stinnerebca3922013-10-26 09:20:38 +0200628 timeout = deadline - _time()
Charles-François Natali64590252013-10-21 14:02:12 +0200629 if not ready:
630 if timeout < 0:
631 break
632 else:
633 continue
634 self.fill_rawq()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000635 text = self.read_very_lazy()
636 if not text and self.eof:
637 raise EOFError
638 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000639
R David Murray4f098062015-11-28 12:24:52 -0500640 def __enter__(self):
641 return self
642
643 def __exit__(self, type, value, traceback):
644 self.close()
645
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000646
647def test():
648 """Test program for telnetlib.
649
650 Usage: python telnetlib.py [-d] ... [host [port]]
651
652 Default host is localhost; default port is 23.
653
654 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000655 debuglevel = 0
656 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000657 debuglevel = debuglevel+1
658 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000659 host = 'localhost'
660 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000661 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000662 port = 0
663 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000664 portstr = sys.argv[2]
665 try:
666 port = int(portstr)
667 except ValueError:
668 port = socket.getservbyname(portstr, 'tcp')
R David Murray4f098062015-11-28 12:24:52 -0500669 with Telnet() as tn:
670 tn.set_debuglevel(debuglevel)
671 tn.open(host, port, timeout=0.5)
672 tn.interact()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000673
674if __name__ == '__main__':
675 test()