blob: d49d4f41affba000e922a5d63b2deb37b9929cdb [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
Victor Stinner2ff68dd2013-10-26 09:16:29 +020041try:
42 from time import monotonic as _time
43except ImportError:
44 from time import time as _time
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000045
Skip Montanaro40fc1602001-03-01 04:27:19 +000046__all__ = ["Telnet"]
47
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000048# Tunable parameters
49DEBUGLEVEL = 0
50
51# Telnet protocol defaults
52TELNET_PORT = 23
53
54# Telnet protocol characters (don't change)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000055IAC = bytes([255]) # "Interpret As Command"
56DONT = bytes([254])
57DO = bytes([253])
58WONT = bytes([252])
59WILL = bytes([251])
60theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000061
Jack Diederich1c8f38c2009-04-10 05:33:26 +000062SE = bytes([240]) # Subnegotiation End
63NOP = bytes([241]) # No Operation
64DM = bytes([242]) # Data Mark
65BRK = bytes([243]) # Break
66IP = bytes([244]) # Interrupt process
67AO = bytes([245]) # Abort output
68AYT = bytes([246]) # Are You There
69EC = bytes([247]) # Erase Character
70EL = bytes([248]) # Erase Line
71GA = bytes([249]) # Go Ahead
72SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000073
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000074
Martin v. Löwisb0162f92001-09-06 08:51:38 +000075# Telnet protocol options code (don't change)
76# These ones all come from arpa/telnet.h
Jack Diederich1c8f38c2009-04-10 05:33:26 +000077BINARY = bytes([0]) # 8-bit data path
78ECHO = bytes([1]) # echo
79RCP = bytes([2]) # prepare to reconnect
80SGA = bytes([3]) # suppress go ahead
81NAMS = bytes([4]) # approximate message size
82STATUS = bytes([5]) # give status
83TM = bytes([6]) # timing mark
84RCTE = bytes([7]) # remote controlled transmission and echo
85NAOL = bytes([8]) # negotiate about output line width
86NAOP = bytes([9]) # negotiate about output page size
87NAOCRD = bytes([10]) # negotiate about CR disposition
88NAOHTS = bytes([11]) # negotiate about horizontal tabstops
89NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
90NAOFFD = bytes([13]) # negotiate about formfeed disposition
91NAOVTS = bytes([14]) # negotiate about vertical tab stops
92NAOVTD = bytes([15]) # negotiate about vertical tab disposition
93NAOLFD = bytes([16]) # negotiate about output LF disposition
94XASCII = bytes([17]) # extended ascii character set
95LOGOUT = bytes([18]) # force logout
96BM = bytes([19]) # byte macro
97DET = bytes([20]) # data entry terminal
98SUPDUP = bytes([21]) # supdup protocol
99SUPDUPOUTPUT = bytes([22]) # supdup output
100SNDLOC = bytes([23]) # send location
101TTYPE = bytes([24]) # terminal type
102EOR = bytes([25]) # end or record
103TUID = bytes([26]) # TACACS user identification
104OUTMRK = bytes([27]) # output marking
105TTYLOC = bytes([28]) # terminal location number
106VT3270REGIME = bytes([29]) # 3270 regime
107X3PAD = bytes([30]) # X.3 PAD
108NAWS = bytes([31]) # window size
109TSPEED = bytes([32]) # terminal speed
110LFLOW = bytes([33]) # remote flow control
111LINEMODE = bytes([34]) # Linemode option
112XDISPLOC = bytes([35]) # X Display Location
113OLD_ENVIRON = bytes([36]) # Old - Environment variables
114AUTHENTICATION = bytes([37]) # Authenticate
115ENCRYPT = bytes([38]) # Encryption option
116NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000117# the following ones come from
118# http://www.iana.org/assignments/telnet-options
119# Unfortunately, that document does not assign identifiers
120# to all of them, so we are making them up
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000121TN3270E = bytes([40]) # TN3270E
122XAUTH = bytes([41]) # XAUTH
123CHARSET = bytes([42]) # CHARSET
124RSP = bytes([43]) # Telnet Remote Serial Port
125COM_PORT_OPTION = bytes([44]) # Com Port Control Option
126SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
127TLS = bytes([46]) # Telnet Start TLS
128KERMIT = bytes([47]) # KERMIT
129SEND_URL = bytes([48]) # SEND-URL
130FORWARD_X = bytes([49]) # FORWARD_X
131PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
132SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
133PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
134EXOPL = bytes([255]) # Extended-Options-List
135NOOPT = bytes([0])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000136
137class Telnet:
138
139 """Telnet interface class.
140
141 An instance of this class represents a connection to a telnet
142 server. The instance is initially not connected; the open()
143 method must be used to establish a connection. Alternatively, the
144 host name and optional port number can be passed to the
145 constructor, too.
146
147 Don't try to reopen an already connected instance.
148
149 This class has many read_*() methods. Note that some of them
150 raise EOFError when the end of the connection is read, because
151 they can return an empty string for other reasons. See the
152 individual doc strings.
153
154 read_until(expected, [timeout])
155 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000156 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000157
158 read_all()
159 Read all data until EOF; may block.
160
161 read_some()
162 Read at least one byte or EOF; may block.
163
164 read_very_eager()
165 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000166 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000167
168 read_eager()
169 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000170 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000171
172 read_lazy()
173 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000175
176 read_very_lazy()
177 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000179
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000180 read_sb_data()
181 Reads available data between SB ... SE sequence. Don't block.
182
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000183 set_option_negotiation_callback(callback)
184 Each time a telnet option is read on the input flow, this callback
185 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000186 callback(telnet socket, command, option)
187 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000188 No other action is done afterwards by telnetlib.
189
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000190 """
191
Georg Brandlf78e02b2008-06-10 17:40:04 +0000192 def __init__(self, host=None, port=0,
193 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000195
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000197 With a hostname argument, it connects the instance; port number
198 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 """
200 self.debuglevel = DEBUGLEVEL
201 self.host = host
202 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000203 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000205 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000207 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000209 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000210 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000211 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000212 self.option_callback = None
Gregory P. Smithdad57112012-07-15 23:42:26 -0700213 self._has_poll = hasattr(select, 'poll')
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000214 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000215 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000216
Georg Brandlf78e02b2008-06-10 17:40:04 +0000217 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000219
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000220 The optional second argument is the port number, which
221 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000222
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000223 Don't try to reopen an already connected instance.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 """
225 self.eof = 0
226 if not port:
227 port = TELNET_PORT
228 self.host = host
229 self.port = port
Georg Brandlf78e02b2008-06-10 17:40:04 +0000230 self.timeout = timeout
231 self.sock = socket.create_connection((host, port), timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000232
233 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 """Destructor -- close the connection."""
235 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000236
237 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000239
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 If extra arguments are present, they are substituted in the
241 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000242
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 """
244 if self.debuglevel > 0:
R. David Murray32ef70c2010-12-14 14:16:20 +0000245 print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000247 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000249 print(msg)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000250
251 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000253
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000255
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000256 """
257 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000258
259 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 """Close the connection."""
261 if self.sock:
262 self.sock.close()
263 self.sock = 0
264 self.eof = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000265 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000266 self.sb = 0
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000267
268 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000269 """Return the socket object used internally."""
270 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000271
272 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 """Return the fileno() of the socket object used internally."""
274 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000275
276 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000277 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000278
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 Can block if the connection is blocked. May raise
280 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000281
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000282 """
283 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000284 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000285 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000286 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000287
288 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000289 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000290
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000291 When no match is found, return whatever is available instead,
292 possibly the empty string. Raise EOFError if the connection
293 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000294
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700296 if self._has_poll:
297 return self._read_until_with_poll(match, timeout)
298 else:
299 return self._read_until_with_select(match, timeout)
300
301 def _read_until_with_poll(self, match, timeout):
302 """Read until a given string is encountered or until timeout.
303
304 This method uses select.poll() to implement the timeout.
305 """
306 n = len(match)
307 call_timeout = timeout
308 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200309 time_start = _time()
Gregory P. Smithdad57112012-07-15 23:42:26 -0700310 self.process_rawq()
311 i = self.cookedq.find(match)
312 if i < 0:
313 poller = select.poll()
314 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
315 poller.register(self, poll_in_or_priority_flags)
316 while i < 0 and not self.eof:
317 try:
Gregory P. Smithacd17302013-12-10 18:25:21 -0800318 ready = poller.poll(None if timeout is None
319 else 1000 * call_timeout)
Gregory P. Smithdad57112012-07-15 23:42:26 -0700320 except select.error as e:
321 if e.errno == errno.EINTR:
322 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200323 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700324 call_timeout = timeout-elapsed
325 continue
326 raise
327 for fd, mode in ready:
328 if mode & poll_in_or_priority_flags:
329 i = max(0, len(self.cookedq)-n)
330 self.fill_rawq()
331 self.process_rawq()
332 i = self.cookedq.find(match, i)
333 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200334 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700335 if elapsed >= timeout:
336 break
337 call_timeout = timeout-elapsed
338 poller.unregister(self)
339 if i >= 0:
340 i = i + n
341 buf = self.cookedq[:i]
342 self.cookedq = self.cookedq[i:]
343 return buf
344 return self.read_very_lazy()
345
346 def _read_until_with_select(self, match, timeout=None):
347 """Read until a given string is encountered or until timeout.
348
349 The timeout is implemented using select.select().
350 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 n = len(match)
352 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000353 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000354 if i >= 0:
355 i = i+n
356 buf = self.cookedq[:i]
357 self.cookedq = self.cookedq[i:]
358 return buf
359 s_reply = ([self], [], [])
360 s_args = s_reply
361 if timeout is not None:
362 s_args = s_args + (timeout,)
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200363 time_start = _time()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000364 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000365 i = max(0, len(self.cookedq)-n)
366 self.fill_rawq()
367 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000368 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000369 if i >= 0:
370 i = i+n
371 buf = self.cookedq[:i]
372 self.cookedq = self.cookedq[i:]
373 return buf
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000374 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200375 elapsed = _time() - time_start
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000376 if elapsed >= timeout:
377 break
378 s_args = s_reply + (timeout-elapsed,)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000380
381 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000382 """Read all data until EOF; block until connection closed."""
383 self.process_rawq()
384 while not self.eof:
385 self.fill_rawq()
386 self.process_rawq()
387 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000388 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000390
391 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000392 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000393
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000394 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000395 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000396
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000397 """
398 self.process_rawq()
399 while not self.cookedq and not self.eof:
400 self.fill_rawq()
401 self.process_rawq()
402 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000403 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000404 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000405
406 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000407 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000408
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000409 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000410 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000411 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000412
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000413 """
414 self.process_rawq()
415 while not self.eof and self.sock_avail():
416 self.fill_rawq()
417 self.process_rawq()
418 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000419
420 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000421 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000422
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000424 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000426
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000427 """
428 self.process_rawq()
429 while not self.cookedq and not self.eof and self.sock_avail():
430 self.fill_rawq()
431 self.process_rawq()
432 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000433
434 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000435 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000436
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000437 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000438 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000440
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000441 """
442 self.process_rawq()
443 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000444
445 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000446 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000447
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000448 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000449 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000450
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000451 """
452 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000453 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000454 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000455 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000456 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000457
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000458 def read_sb_data(self):
459 """Return any data available in the SB ... SE queue.
460
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000461 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000462 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000463 found, old unread SB data will be discarded. Don't block.
464
465 """
466 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000467 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000468 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000469
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000470 def set_option_negotiation_callback(self, callback):
471 """Provide a callback function called after each receipt of a telnet option."""
472 self.option_callback = callback
473
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000474 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000475 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000476
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000477 Set self.eof when connection is closed. Don't block unless in
478 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000479
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000480 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000481 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000482 try:
483 while self.rawq:
484 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000485 if not self.iacseq:
486 if c == theNULL:
487 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000488 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000489 continue
490 if c != IAC:
491 buf[self.sb] = buf[self.sb] + c
492 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000493 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000494 self.iacseq += c
495 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000496 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000497 if c in (DO, DONT, WILL, WONT):
498 self.iacseq += c
499 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000500
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000501 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000502 if c == IAC:
503 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000504 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000505 if c == SB: # SB ... SE start.
506 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000507 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000508 elif c == SE:
509 self.sb = 0
510 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000511 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000512 if self.option_callback:
513 # Callback is supposed to look into
514 # the sbdataq
515 self.option_callback(self.sock, c, NOOPT)
516 else:
517 # We can't offer automatic processing of
518 # suboptions. Alas, we should not get any
519 # unless we did a WILL/DO before.
520 self.msg('IAC %d not recognized' % ord(c))
521 elif len(self.iacseq) == 2:
Jack Diederich36596a32009-07-26 22:23:04 +0000522 cmd = self.iacseq[1:2]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000523 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000524 opt = c
525 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000526 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000527 cmd == DO and 'DO' or 'DONT', ord(opt))
528 if self.option_callback:
529 self.option_callback(self.sock, cmd, opt)
530 else:
531 self.sock.sendall(IAC + WONT + opt)
532 elif cmd in (WILL, WONT):
533 self.msg('IAC %s %d',
534 cmd == WILL and 'WILL' or 'WONT', ord(opt))
535 if self.option_callback:
536 self.option_callback(self.sock, cmd, opt)
537 else:
538 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000539 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000540 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000541 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000542 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000543 self.cookedq = self.cookedq + buf[0]
544 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000545
546 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000547 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000548
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000549 Block if no data is immediately available. Raise EOFError
550 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000551
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000552 """
553 if not self.rawq:
554 self.fill_rawq()
555 if self.eof:
556 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000557 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000558 self.irawq = self.irawq + 1
559 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000560 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000561 self.irawq = 0
562 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000563
564 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000565 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000566
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000567 Block if no data is immediately available. Set self.eof when
568 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000569
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000570 """
571 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000572 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000573 self.irawq = 0
574 # The buffer size should be fairly small so as to avoid quadratic
575 # behavior in process_rawq() above
576 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000577 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000578 self.eof = (not buf)
579 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000580
581 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000582 """Test whether data is available on the socket."""
583 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000584
585 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000586 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000587 if sys.platform == "win32":
588 self.mt_interact()
589 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000590 while 1:
591 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
592 if self in rfd:
593 try:
594 text = self.read_eager()
595 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000596 print('*** Connection closed by remote host ***')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000597 break
598 if text:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000599 sys.stdout.write(text.decode('ascii'))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000600 sys.stdout.flush()
601 if sys.stdin in rfd:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000602 line = sys.stdin.readline().encode('ascii')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000603 if not line:
604 break
605 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000606
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000607 def mt_interact(self):
608 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000609 import _thread
610 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000611 while 1:
612 line = sys.stdin.readline()
613 if not line:
614 break
R. David Murrayba488d12010-10-26 12:42:24 +0000615 self.write(line.encode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000616
617 def listener(self):
618 """Helper for mt_interact() -- this executes in the other thread."""
619 while 1:
620 try:
621 data = self.read_eager()
622 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000623 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000624 return
625 if data:
R. David Murrayba488d12010-10-26 12:42:24 +0000626 sys.stdout.write(data.decode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000627 else:
628 sys.stdout.flush()
629
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000630 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000631 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000632
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000633 The first argument is a list of regular expressions, either
634 compiled (re.RegexObject instances) or uncompiled (strings).
635 The optional second argument is a timeout, in seconds; default
636 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000637
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000638 Return a tuple of three items: the index in the list of the
639 first regular expression that matches; the match object
640 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000641
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000642 If EOF is read and no text was read, raise EOFError.
643 Otherwise, when nothing matches, return (-1, None, text) where
644 text is the text received so far (may be the empty string if a
645 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000646
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000647 If a regular expression ends with a greedy match (e.g. '.*')
648 or if more than one expression can match the same input, the
649 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000650
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000651 """
Gregory P. Smithdad57112012-07-15 23:42:26 -0700652 if self._has_poll:
653 return self._expect_with_poll(list, timeout)
654 else:
655 return self._expect_with_select(list, timeout)
656
657 def _expect_with_poll(self, expect_list, timeout=None):
658 """Read until one from a list of a regular expressions matches.
659
660 This method uses select.poll() to implement the timeout.
661 """
662 re = None
663 expect_list = expect_list[:]
664 indices = range(len(expect_list))
665 for i in indices:
666 if not hasattr(expect_list[i], "search"):
667 if not re: import re
668 expect_list[i] = re.compile(expect_list[i])
669 call_timeout = timeout
670 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200671 time_start = _time()
Gregory P. Smithdad57112012-07-15 23:42:26 -0700672 self.process_rawq()
673 m = None
674 for i in indices:
675 m = expect_list[i].search(self.cookedq)
676 if m:
677 e = m.end()
678 text = self.cookedq[:e]
679 self.cookedq = self.cookedq[e:]
680 break
681 if not m:
682 poller = select.poll()
683 poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
684 poller.register(self, poll_in_or_priority_flags)
685 while not m and not self.eof:
686 try:
Gregory P. Smithacd17302013-12-10 18:25:21 -0800687 ready = poller.poll(None if timeout is None
688 else 1000 * call_timeout)
Gregory P. Smithdad57112012-07-15 23:42:26 -0700689 except select.error as e:
690 if e.errno == errno.EINTR:
691 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200692 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700693 call_timeout = timeout-elapsed
694 continue
695 raise
696 for fd, mode in ready:
697 if mode & poll_in_or_priority_flags:
698 self.fill_rawq()
699 self.process_rawq()
700 for i in indices:
701 m = expect_list[i].search(self.cookedq)
702 if m:
703 e = m.end()
704 text = self.cookedq[:e]
705 self.cookedq = self.cookedq[e:]
706 break
707 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200708 elapsed = _time() - time_start
Gregory P. Smithdad57112012-07-15 23:42:26 -0700709 if elapsed >= timeout:
710 break
711 call_timeout = timeout-elapsed
712 poller.unregister(self)
713 if m:
714 return (i, m, text)
715 text = self.read_very_lazy()
716 if not text and self.eof:
717 raise EOFError
718 return (-1, None, text)
719
720 def _expect_with_select(self, list, timeout=None):
721 """Read until one from a list of a regular expressions matches.
722
723 The timeout is implemented using select.select().
724 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000725 re = None
726 list = list[:]
727 indices = range(len(list))
728 for i in indices:
729 if not hasattr(list[i], "search"):
730 if not re: import re
731 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000732 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200733 time_start = _time()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000734 while 1:
735 self.process_rawq()
736 for i in indices:
737 m = list[i].search(self.cookedq)
738 if m:
739 e = m.end()
740 text = self.cookedq[:e]
741 self.cookedq = self.cookedq[e:]
742 return (i, m, text)
743 if self.eof:
744 break
745 if timeout is not None:
Victor Stinner2ff68dd2013-10-26 09:16:29 +0200746 elapsed = _time() - time_start
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000747 if elapsed >= timeout:
748 break
749 s_args = ([self.fileno()], [], [], timeout-elapsed)
750 r, w, x = select.select(*s_args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000751 if not r:
752 break
753 self.fill_rawq()
754 text = self.read_very_lazy()
755 if not text and self.eof:
756 raise EOFError
757 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000758
759
760def test():
761 """Test program for telnetlib.
762
763 Usage: python telnetlib.py [-d] ... [host [port]]
764
765 Default host is localhost; default port is 23.
766
767 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000768 debuglevel = 0
769 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000770 debuglevel = debuglevel+1
771 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000772 host = 'localhost'
773 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000774 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000775 port = 0
776 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000777 portstr = sys.argv[2]
778 try:
779 port = int(portstr)
780 except ValueError:
781 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000782 tn = Telnet()
783 tn.set_debuglevel(debuglevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000784 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000785 tn.interact()
786 tn.close()
787
788if __name__ == '__main__':
789 test()