blob: b4b7cd4df3c9f008846dd164cfba1d1b6ef7e200 [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
20It is possible to pass a Telnet object to select.select() in order to
21wait until more data is available. Note that in this case,
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000022read_eager() may return b'' even if there was data on the socket,
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000023because the protocol negotiation may have eaten the data. This is why
24EOFError is needed in some cases to distinguish between "no data" and
25"connection closed" (since the socket also appears ready for reading
26when it is closed).
27
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000028To do:
29- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000030- timeout should be intrinsic to the connection object instead of an
31 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000032
33"""
34
35
36# Imported modules
Gregory P. Smithdad57112012-07-15 23:42:26 -070037import errno
Guido van Rossumccb5ec61997-12-24 22:24:19 +000038import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000039import socket
40import select
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000041
Skip Montanaro40fc1602001-03-01 04:27:19 +000042__all__ = ["Telnet"]
43
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000044# Tunable parameters
45DEBUGLEVEL = 0
46
47# Telnet protocol defaults
48TELNET_PORT = 23
49
50# Telnet protocol characters (don't change)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000051IAC = bytes([255]) # "Interpret As Command"
52DONT = bytes([254])
53DO = bytes([253])
54WONT = bytes([252])
55WILL = bytes([251])
56theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000057
Jack Diederich1c8f38c2009-04-10 05:33:26 +000058SE = bytes([240]) # Subnegotiation End
59NOP = bytes([241]) # No Operation
60DM = bytes([242]) # Data Mark
61BRK = bytes([243]) # Break
62IP = bytes([244]) # Interrupt process
63AO = bytes([245]) # Abort output
64AYT = bytes([246]) # Are You There
65EC = bytes([247]) # Erase Character
66EL = bytes([248]) # Erase Line
67GA = bytes([249]) # Go Ahead
68SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000069
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000070
Martin v. Löwisb0162f92001-09-06 08:51:38 +000071# Telnet protocol options code (don't change)
72# These ones all come from arpa/telnet.h
Jack Diederich1c8f38c2009-04-10 05:33:26 +000073BINARY = bytes([0]) # 8-bit data path
74ECHO = bytes([1]) # echo
75RCP = bytes([2]) # prepare to reconnect
76SGA = bytes([3]) # suppress go ahead
77NAMS = bytes([4]) # approximate message size
78STATUS = bytes([5]) # give status
79TM = bytes([6]) # timing mark
80RCTE = bytes([7]) # remote controlled transmission and echo
81NAOL = bytes([8]) # negotiate about output line width
82NAOP = bytes([9]) # negotiate about output page size
83NAOCRD = bytes([10]) # negotiate about CR disposition
84NAOHTS = bytes([11]) # negotiate about horizontal tabstops
85NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
86NAOFFD = bytes([13]) # negotiate about formfeed disposition
87NAOVTS = bytes([14]) # negotiate about vertical tab stops
88NAOVTD = bytes([15]) # negotiate about vertical tab disposition
89NAOLFD = bytes([16]) # negotiate about output LF disposition
90XASCII = bytes([17]) # extended ascii character set
91LOGOUT = bytes([18]) # force logout
92BM = bytes([19]) # byte macro
93DET = bytes([20]) # data entry terminal
94SUPDUP = bytes([21]) # supdup protocol
95SUPDUPOUTPUT = bytes([22]) # supdup output
96SNDLOC = bytes([23]) # send location
97TTYPE = bytes([24]) # terminal type
98EOR = bytes([25]) # end or record
99TUID = bytes([26]) # TACACS user identification
100OUTMRK = bytes([27]) # output marking
101TTYLOC = bytes([28]) # terminal location number
102VT3270REGIME = bytes([29]) # 3270 regime
103X3PAD = bytes([30]) # X.3 PAD
104NAWS = bytes([31]) # window size
105TSPEED = bytes([32]) # terminal speed
106LFLOW = bytes([33]) # remote flow control
107LINEMODE = bytes([34]) # Linemode option
108XDISPLOC = bytes([35]) # X Display Location
109OLD_ENVIRON = bytes([36]) # Old - Environment variables
110AUTHENTICATION = bytes([37]) # Authenticate
111ENCRYPT = bytes([38]) # Encryption option
112NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000113# the following ones come from
114# http://www.iana.org/assignments/telnet-options
115# Unfortunately, that document does not assign identifiers
116# to all of them, so we are making them up
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000117TN3270E = bytes([40]) # TN3270E
118XAUTH = bytes([41]) # XAUTH
119CHARSET = bytes([42]) # CHARSET
120RSP = bytes([43]) # Telnet Remote Serial Port
121COM_PORT_OPTION = bytes([44]) # Com Port Control Option
122SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
123TLS = bytes([46]) # Telnet Start TLS
124KERMIT = bytes([47]) # KERMIT
125SEND_URL = bytes([48]) # SEND-URL
126FORWARD_X = bytes([49]) # FORWARD_X
127PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
128SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
129PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
130EXOPL = bytes([255]) # Extended-Options-List
131NOOPT = bytes([0])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000132
133class Telnet:
134
135 """Telnet interface class.
136
137 An instance of this class represents a connection to a telnet
138 server. The instance is initially not connected; the open()
139 method must be used to establish a connection. Alternatively, the
140 host name and optional port number can be passed to the
141 constructor, too.
142
143 Don't try to reopen an already connected instance.
144
145 This class has many read_*() methods. Note that some of them
146 raise EOFError when the end of the connection is read, because
147 they can return an empty string for other reasons. See the
148 individual doc strings.
149
150 read_until(expected, [timeout])
151 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000152 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000153
154 read_all()
155 Read all data until EOF; may block.
156
157 read_some()
158 Read at least one byte or EOF; may block.
159
160 read_very_eager()
161 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000163
164 read_eager()
165 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000167
168 read_lazy()
169 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000171
172 read_very_lazy()
173 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000175
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000176 read_sb_data()
177 Reads available data between SB ... SE sequence. Don't block.
178
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000179 set_option_negotiation_callback(callback)
180 Each time a telnet option is read on the input flow, this callback
181 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000182 callback(telnet socket, command, option)
183 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000184 No other action is done afterwards by telnetlib.
185
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000186 """
187
Georg Brandlf78e02b2008-06-10 17:40:04 +0000188 def __init__(self, host=None, port=0,
189 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000191
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000192 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000193 With a hostname argument, it connects the instance; port number
194 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000195 """
196 self.debuglevel = DEBUGLEVEL
197 self.host = host
198 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000199 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000201 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000202 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000203 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000205 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000206 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000207 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000208 self.option_callback = None
Gregory P. Smithdad57112012-07-15 23:42:26 -0700209 self._has_poll = hasattr(select, 'poll')
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000210 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000211 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000212
Georg Brandlf78e02b2008-06-10 17:40:04 +0000213 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000215
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000216 The optional second argument is the port number, which
217 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000218
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000219 Don't try to reopen an already connected instance.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 """
221 self.eof = 0
222 if not port:
223 port = TELNET_PORT
224 self.host = host
225 self.port = port
Georg Brandlf78e02b2008-06-10 17:40:04 +0000226 self.timeout = timeout
227 self.sock = socket.create_connection((host, port), timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000228
229 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 """Destructor -- close the connection."""
231 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000232
233 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000235
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000236 If extra arguments are present, they are substituted in the
237 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000238
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 """
240 if self.debuglevel > 0:
R. David Murray32ef70c2010-12-14 14:16:20 +0000241 print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000244 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000245 print(msg)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000246
247 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000249
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000250 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000251
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 """
253 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000254
255 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 """Close the connection."""
257 if self.sock:
258 self.sock.close()
259 self.sock = 0
260 self.eof = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000261 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000262 self.sb = 0
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000263
264 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 """Return the socket object used internally."""
266 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000267
268 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 """Return the fileno() of the socket object used internally."""
270 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000271
272 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000274
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 Can block if the connection is blocked. May raise
Andrew Svetlov0832af62012-12-18 23:10:48 +0200276 OSError if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000277
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000278 """
279 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000280 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000281 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000282 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000283
284 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000286
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000287 When no match is found, return whatever is available instead,
288 possibly the empty string. Raise EOFError if the connection
289 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000290
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700292 if self._has_poll:
293 return self._read_until_with_poll(match, timeout)
294 else:
295 return self._read_until_with_select(match, timeout)
296
297 def _read_until_with_poll(self, match, timeout):
298 """Read until a given string is encountered or until timeout.
299
300 This method uses select.poll() to implement the timeout.
301 """
302 n = len(match)
303 call_timeout = timeout
304 if timeout is not None:
305 from time import time
306 time_start = time()
307 self.process_rawq()
308 i = self.cookedq.find(match)
309 if i < 0:
310 poller = select.poll()
311 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
312 poller.register(self, poll_in_or_priority_flags)
313 while i < 0 and not self.eof:
314 try:
315 ready = poller.poll(call_timeout)
Andrew Svetlov6d8a1222012-12-17 22:23:46 +0200316 except OSError as e:
Gregory P. Smithdad57112012-07-15 23:42:26 -0700317 if e.errno == errno.EINTR:
318 if timeout is not None:
319 elapsed = time() - time_start
320 call_timeout = timeout-elapsed
321 continue
322 raise
323 for fd, mode in ready:
324 if mode & poll_in_or_priority_flags:
325 i = max(0, len(self.cookedq)-n)
326 self.fill_rawq()
327 self.process_rawq()
328 i = self.cookedq.find(match, i)
329 if timeout is not None:
330 elapsed = time() - time_start
331 if elapsed >= timeout:
332 break
333 call_timeout = timeout-elapsed
334 poller.unregister(self)
335 if i >= 0:
336 i = i + n
337 buf = self.cookedq[:i]
338 self.cookedq = self.cookedq[i:]
339 return buf
340 return self.read_very_lazy()
341
342 def _read_until_with_select(self, match, timeout=None):
343 """Read until a given string is encountered or until timeout.
344
345 The timeout is implemented using select.select().
346 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 n = len(match)
348 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000349 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000350 if i >= 0:
351 i = i+n
352 buf = self.cookedq[:i]
353 self.cookedq = self.cookedq[i:]
354 return buf
355 s_reply = ([self], [], [])
356 s_args = s_reply
357 if timeout is not None:
358 s_args = s_args + (timeout,)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000359 from time import time
360 time_start = time()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000361 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 i = max(0, len(self.cookedq)-n)
363 self.fill_rawq()
364 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000365 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000366 if i >= 0:
367 i = i+n
368 buf = self.cookedq[:i]
369 self.cookedq = self.cookedq[i:]
370 return buf
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000371 if timeout is not None:
372 elapsed = time() - time_start
373 if elapsed >= timeout:
374 break
375 s_args = s_reply + (timeout-elapsed,)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000376 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000377
378 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 """Read all data until EOF; block until connection closed."""
380 self.process_rawq()
381 while not self.eof:
382 self.fill_rawq()
383 self.process_rawq()
384 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000385 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000386 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000387
388 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000390
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000391 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000392 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000393
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 """
395 self.process_rawq()
396 while not self.cookedq and not self.eof:
397 self.fill_rawq()
398 self.process_rawq()
399 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000400 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000401 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000402
403 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000404 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000405
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000407 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000409
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000410 """
411 self.process_rawq()
412 while not self.eof and self.sock_avail():
413 self.fill_rawq()
414 self.process_rawq()
415 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000416
417 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000418 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000419
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000421 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000423
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 """
425 self.process_rawq()
426 while not self.cookedq and not self.eof and self.sock_avail():
427 self.fill_rawq()
428 self.process_rawq()
429 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000430
431 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000432 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000433
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000434 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000435 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000437
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000438 """
439 self.process_rawq()
440 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000441
442 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000444
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000446 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000447
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000448 """
449 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000450 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000451 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000452 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000453 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000454
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000455 def read_sb_data(self):
456 """Return any data available in the SB ... SE queue.
457
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000458 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000459 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000460 found, old unread SB data will be discarded. Don't block.
461
462 """
463 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000464 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000465 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000466
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000467 def set_option_negotiation_callback(self, callback):
468 """Provide a callback function called after each receipt of a telnet option."""
469 self.option_callback = callback
470
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000471 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000473
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000474 Set self.eof when connection is closed. Don't block unless in
475 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000476
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000477 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000478 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000479 try:
480 while self.rawq:
481 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000482 if not self.iacseq:
483 if c == theNULL:
484 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000485 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000486 continue
487 if c != IAC:
488 buf[self.sb] = buf[self.sb] + c
489 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000490 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000491 self.iacseq += c
492 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000493 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000494 if c in (DO, DONT, WILL, WONT):
495 self.iacseq += c
496 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000497
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000498 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000499 if c == IAC:
500 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000501 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000502 if c == SB: # SB ... SE start.
503 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000504 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000505 elif c == SE:
506 self.sb = 0
507 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000508 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000509 if self.option_callback:
510 # Callback is supposed to look into
511 # the sbdataq
512 self.option_callback(self.sock, c, NOOPT)
513 else:
514 # We can't offer automatic processing of
515 # suboptions. Alas, we should not get any
516 # unless we did a WILL/DO before.
517 self.msg('IAC %d not recognized' % ord(c))
518 elif len(self.iacseq) == 2:
Jack Diederich36596a32009-07-26 22:23:04 +0000519 cmd = self.iacseq[1:2]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000520 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000521 opt = c
522 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000523 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000524 cmd == DO and 'DO' or 'DONT', ord(opt))
525 if self.option_callback:
526 self.option_callback(self.sock, cmd, opt)
527 else:
528 self.sock.sendall(IAC + WONT + opt)
529 elif cmd in (WILL, WONT):
530 self.msg('IAC %s %d',
531 cmd == WILL and 'WILL' or 'WONT', ord(opt))
532 if self.option_callback:
533 self.option_callback(self.sock, cmd, opt)
534 else:
535 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000536 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000537 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000538 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000539 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000540 self.cookedq = self.cookedq + buf[0]
541 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000542
543 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000544 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000545
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000546 Block if no data is immediately available. Raise EOFError
547 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000548
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000549 """
550 if not self.rawq:
551 self.fill_rawq()
552 if self.eof:
553 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000554 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000555 self.irawq = self.irawq + 1
556 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000557 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000558 self.irawq = 0
559 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000560
561 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000562 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000563
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000564 Block if no data is immediately available. Set self.eof when
565 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000566
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000567 """
568 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000569 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000570 self.irawq = 0
571 # The buffer size should be fairly small so as to avoid quadratic
572 # behavior in process_rawq() above
573 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000574 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000575 self.eof = (not buf)
576 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000577
578 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000579 """Test whether data is available on the socket."""
580 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000581
582 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000583 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000584 if sys.platform == "win32":
585 self.mt_interact()
586 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 while 1:
588 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
589 if self in rfd:
590 try:
591 text = self.read_eager()
592 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000593 print('*** Connection closed by remote host ***')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000594 break
595 if text:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000596 sys.stdout.write(text.decode('ascii'))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000597 sys.stdout.flush()
598 if sys.stdin in rfd:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000599 line = sys.stdin.readline().encode('ascii')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000600 if not line:
601 break
602 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000603
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000604 def mt_interact(self):
605 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000606 import _thread
607 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000608 while 1:
609 line = sys.stdin.readline()
610 if not line:
611 break
R. David Murrayba488d12010-10-26 12:42:24 +0000612 self.write(line.encode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000613
614 def listener(self):
615 """Helper for mt_interact() -- this executes in the other thread."""
616 while 1:
617 try:
618 data = self.read_eager()
619 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000620 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000621 return
622 if data:
R. David Murrayba488d12010-10-26 12:42:24 +0000623 sys.stdout.write(data.decode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000624 else:
625 sys.stdout.flush()
626
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000627 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000628 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000629
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000630 The first argument is a list of regular expressions, either
631 compiled (re.RegexObject instances) or uncompiled (strings).
632 The optional second argument is a timeout, in seconds; default
633 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000634
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000635 Return a tuple of three items: the index in the list of the
636 first regular expression that matches; the match object
637 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000638
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000639 If EOF is read and no text was read, raise EOFError.
640 Otherwise, when nothing matches, return (-1, None, text) where
641 text is the text received so far (may be the empty string if a
642 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000643
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000644 If a regular expression ends with a greedy match (e.g. '.*')
645 or if more than one expression can match the same input, the
646 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000647
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000648 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700649 if self._has_poll:
650 return self._expect_with_poll(list, timeout)
651 else:
652 return self._expect_with_select(list, timeout)
653
654 def _expect_with_poll(self, expect_list, timeout=None):
655 """Read until one from a list of a regular expressions matches.
656
657 This method uses select.poll() to implement the timeout.
658 """
659 re = None
660 expect_list = expect_list[:]
661 indices = range(len(expect_list))
662 for i in indices:
663 if not hasattr(expect_list[i], "search"):
664 if not re: import re
665 expect_list[i] = re.compile(expect_list[i])
666 call_timeout = timeout
667 if timeout is not None:
668 from time import time
669 time_start = time()
670 self.process_rawq()
671 m = None
672 for i in indices:
673 m = expect_list[i].search(self.cookedq)
674 if m:
675 e = m.end()
676 text = self.cookedq[:e]
677 self.cookedq = self.cookedq[e:]
678 break
679 if not m:
680 poller = select.poll()
681 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
682 poller.register(self, poll_in_or_priority_flags)
683 while not m and not self.eof:
684 try:
685 ready = poller.poll(call_timeout)
Andrew Svetlov6d8a1222012-12-17 22:23:46 +0200686 except OSError as e:
Gregory P. Smithdad57112012-07-15 23:42:26 -0700687 if e.errno == errno.EINTR:
688 if timeout is not None:
689 elapsed = time() - time_start
690 call_timeout = timeout-elapsed
691 continue
692 raise
693 for fd, mode in ready:
694 if mode & poll_in_or_priority_flags:
695 self.fill_rawq()
696 self.process_rawq()
697 for i in indices:
698 m = expect_list[i].search(self.cookedq)
699 if m:
700 e = m.end()
701 text = self.cookedq[:e]
702 self.cookedq = self.cookedq[e:]
703 break
704 if timeout is not None:
705 elapsed = time() - time_start
706 if elapsed >= timeout:
707 break
708 call_timeout = timeout-elapsed
709 poller.unregister(self)
710 if m:
711 return (i, m, text)
712 text = self.read_very_lazy()
713 if not text and self.eof:
714 raise EOFError
715 return (-1, None, text)
716
717 def _expect_with_select(self, list, timeout=None):
718 """Read until one from a list of a regular expressions matches.
719
720 The timeout is implemented using select.select().
721 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000722 re = None
723 list = list[:]
724 indices = range(len(list))
725 for i in indices:
726 if not hasattr(list[i], "search"):
727 if not re: import re
728 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000729 if timeout is not None:
730 from time import time
731 time_start = time()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000732 while 1:
733 self.process_rawq()
734 for i in indices:
735 m = list[i].search(self.cookedq)
736 if m:
737 e = m.end()
738 text = self.cookedq[:e]
739 self.cookedq = self.cookedq[e:]
740 return (i, m, text)
741 if self.eof:
742 break
743 if timeout is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000744 elapsed = time() - time_start
745 if elapsed >= timeout:
746 break
747 s_args = ([self.fileno()], [], [], timeout-elapsed)
748 r, w, x = select.select(*s_args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000749 if not r:
750 break
751 self.fill_rawq()
752 text = self.read_very_lazy()
753 if not text and self.eof:
754 raise EOFError
755 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000756
757
758def test():
759 """Test program for telnetlib.
760
761 Usage: python telnetlib.py [-d] ... [host [port]]
762
763 Default host is localhost; default port is 23.
764
765 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000766 debuglevel = 0
767 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000768 debuglevel = debuglevel+1
769 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000770 host = 'localhost'
771 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000772 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000773 port = 0
774 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000775 portstr = sys.argv[2]
776 try:
777 port = int(portstr)
778 except ValueError:
779 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000780 tn = Telnet()
781 tn.set_debuglevel(debuglevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000782 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000783 tn.interact()
784 tn.close()
785
786if __name__ == '__main__':
787 test()