blob: 88aa482d014db49ba7c7ed77f51e309cf5292d2e [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
10>>> tn.write('guido\r\n')
11>>> print tn.read_all()
12Login 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,
22read_eager() may return '' even if there was data on the socket,
23because 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. Smithe0c22202012-07-15 22:16:06 -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)
51IAC = chr(255) # "Interpret As Command"
52DONT = chr(254)
53DO = chr(253)
54WONT = chr(252)
55WILL = chr(251)
56theNULL = chr(0)
Martin v. Löwis574deae2002-11-04 17:34:07 +000057
58SE = chr(240) # Subnegotiation End
59NOP = chr(241) # No Operation
60DM = chr(242) # Data Mark
61BRK = chr(243) # Break
62IP = chr(244) # Interrupt process
63AO = chr(245) # Abort output
64AYT = chr(246) # Are You There
65EC = chr(247) # Erase Character
66EL = chr(248) # Erase Line
67GA = chr(249) # Go Ahead
68SB = chr(250) # Subnegotiation Begin
69
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
73BINARY = chr(0) # 8-bit data path
74ECHO = chr(1) # echo
75RCP = chr(2) # prepare to reconnect
76SGA = chr(3) # suppress go ahead
77NAMS = chr(4) # approximate message size
78STATUS = chr(5) # give status
79TM = chr(6) # timing mark
80RCTE = chr(7) # remote controlled transmission and echo
81NAOL = chr(8) # negotiate about output line width
82NAOP = chr(9) # negotiate about output page size
83NAOCRD = chr(10) # negotiate about CR disposition
84NAOHTS = chr(11) # negotiate about horizontal tabstops
85NAOHTD = chr(12) # negotiate about horizontal tab disposition
86NAOFFD = chr(13) # negotiate about formfeed disposition
87NAOVTS = chr(14) # negotiate about vertical tab stops
88NAOVTD = chr(15) # negotiate about vertical tab disposition
89NAOLFD = chr(16) # negotiate about output LF disposition
90XASCII = chr(17) # extended ascii character set
91LOGOUT = chr(18) # force logout
92BM = chr(19) # byte macro
93DET = chr(20) # data entry terminal
94SUPDUP = chr(21) # supdup protocol
95SUPDUPOUTPUT = chr(22) # supdup output
96SNDLOC = chr(23) # send location
97TTYPE = chr(24) # terminal type
98EOR = chr(25) # end or record
99TUID = chr(26) # TACACS user identification
100OUTMRK = chr(27) # output marking
101TTYLOC = chr(28) # terminal location number
102VT3270REGIME = chr(29) # 3270 regime
103X3PAD = chr(30) # X.3 PAD
104NAWS = chr(31) # window size
105TSPEED = chr(32) # terminal speed
106LFLOW = chr(33) # remote flow control
107LINEMODE = chr(34) # Linemode option
108XDISPLOC = chr(35) # X Display Location
109OLD_ENVIRON = chr(36) # Old - Environment variables
110AUTHENTICATION = chr(37) # Authenticate
111ENCRYPT = chr(38) # Encryption option
112NEW_ENVIRON = chr(39) # New - Environment variables
113# 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
117TN3270E = chr(40) # TN3270E
118XAUTH = chr(41) # XAUTH
119CHARSET = chr(42) # CHARSET
120RSP = chr(43) # Telnet Remote Serial Port
121COM_PORT_OPTION = chr(44) # Com Port Control Option
122SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
123TLS = chr(46) # Telnet Start TLS
124KERMIT = chr(47) # KERMIT
125SEND_URL = chr(48) # SEND-URL
126FORWARD_X = chr(49) # FORWARD_X
127PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
128SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
129PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
130EXOPL = chr(255) # Extended-Options-List
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000131NOOPT = chr(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
Facundo Batista4f1b1ed2008-05-29 16:39:26 +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.
Facundo Batista4f1b1ed2008-05-29 16:39:26 +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
Facundo Batistab6a5c9d2007-03-29 18:22:35 +0000199 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 self.sock = None
201 self.rawq = ''
202 self.irawq = 0
203 self.cookedq = ''
204 self.eof = 0
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000205 self.iacseq = '' # Buffer for IAC sequence.
206 self.sb = 0 # flag for SB and SE sequence.
207 self.sbdataq = ''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000208 self.option_callback = None
Gregory P. Smithe0c22202012-07-15 22:16:06 -0700209 self._has_poll = hasattr(select, 'poll')
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000210 if host is not None:
Facundo Batistab6a5c9d2007-03-29 18:22:35 +0000211 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000212
Facundo Batista4f1b1ed2008-05-29 16:39:26 +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
Facundo Batista4f1b1ed2008-05-29 16:39:26 +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 Murraydacb8042010-12-14 14:34:16 +0000241 print 'Telnet(%s,%s):' % (self.host, self.port),
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 if args:
243 print msg % args
244 else:
245 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
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000261 self.iacseq = ''
262 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
276 socket.error 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. Smithe0c22202012-07-15 22:16:06 -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:
Gregory P. Smith9ffb1482013-12-10 18:22:03 -0800315 # Poll takes its timeout in milliseconds.
316 ready = poller.poll(None if timeout is None
317 else 1000 * call_timeout)
Gregory P. Smithe0c22202012-07-15 22:16:06 -0700318 except select.error as e:
319 if e.errno == errno.EINTR:
320 if timeout is not None:
321 elapsed = time() - time_start
322 call_timeout = timeout-elapsed
323 continue
324 raise
325 for fd, mode in ready:
326 if mode & poll_in_or_priority_flags:
327 i = max(0, len(self.cookedq)-n)
328 self.fill_rawq()
329 self.process_rawq()
330 i = self.cookedq.find(match, i)
331 if timeout is not None:
332 elapsed = time() - time_start
333 if elapsed >= timeout:
334 break
335 call_timeout = timeout-elapsed
336 poller.unregister(self)
337 if i >= 0:
338 i = i + n
339 buf = self.cookedq[:i]
340 self.cookedq = self.cookedq[i:]
341 return buf
342 return self.read_very_lazy()
343
344 def _read_until_with_select(self, match, timeout=None):
345 """Read until a given string is encountered or until timeout.
346
347 The timeout is implemented using select.select().
348 """
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000349 n = len(match)
350 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000351 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000352 if i >= 0:
353 i = i+n
354 buf = self.cookedq[:i]
355 self.cookedq = self.cookedq[i:]
356 return buf
357 s_reply = ([self], [], [])
358 s_args = s_reply
359 if timeout is not None:
360 s_args = s_args + (timeout,)
Martin v. Löwisede77f52006-07-03 13:01:35 +0000361 from time import time
362 time_start = time()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000363 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000364 i = max(0, len(self.cookedq)-n)
365 self.fill_rawq()
366 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000367 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000368 if i >= 0:
369 i = i+n
370 buf = self.cookedq[:i]
371 self.cookedq = self.cookedq[i:]
372 return buf
Martin v. Löwisede77f52006-07-03 13:01:35 +0000373 if timeout is not None:
374 elapsed = time() - time_start
375 if elapsed >= timeout:
376 break
377 s_args = s_reply + (timeout-elapsed,)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000378 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000379
380 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 """Read all data until EOF; block until connection closed."""
382 self.process_rawq()
383 while not self.eof:
384 self.fill_rawq()
385 self.process_rawq()
386 buf = self.cookedq
387 self.cookedq = ''
388 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000389
390 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000392
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000393 Return '' if EOF is hit. Block if no data is immediately
394 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000395
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 """
397 self.process_rawq()
398 while not self.cookedq and not self.eof:
399 self.fill_rawq()
400 self.process_rawq()
401 buf = self.cookedq
402 self.cookedq = ''
403 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000404
405 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000407
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000408 Raise EOFError if connection closed and no cooked data
409 available. Return '' if no cooked data available otherwise.
410 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000411
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000412 """
413 self.process_rawq()
414 while not self.eof and self.sock_avail():
415 self.fill_rawq()
416 self.process_rawq()
417 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000418
419 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000421
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 Raise EOFError if connection closed and no cooked data
423 available. Return '' if no cooked data available otherwise.
424 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000425
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000426 """
427 self.process_rawq()
428 while not self.cookedq and not self.eof and self.sock_avail():
429 self.fill_rawq()
430 self.process_rawq()
431 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000432
433 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000434 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000435
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000436 Raise EOFError if connection closed and no data available.
437 Return '' if no cooked data available otherwise. Don't block
438 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000439
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000440 """
441 self.process_rawq()
442 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000443
444 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000445 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000446
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000447 Raise EOFError if connection closed and no data available.
448 Return '' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000449
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000450 """
451 buf = self.cookedq
452 self.cookedq = ''
453 if not buf and self.eof and not self.rawq:
454 raise EOFError, 'telnet connection closed'
455 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000456
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000457 def read_sb_data(self):
458 """Return any data available in the SB ... SE queue.
459
Tim Peters230a60c2002-11-09 05:08:07 +0000460 Return '' if no SB ... SE available. Should only be called
461 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000462 found, old unread SB data will be discarded. Don't block.
463
464 """
465 buf = self.sbdataq
466 self.sbdataq = ''
467 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000468
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000469 def set_option_negotiation_callback(self, callback):
470 """Provide a callback function called after each receipt of a telnet option."""
471 self.option_callback = callback
472
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000473 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000474 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000475
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000476 Set self.eof when connection is closed. Don't block unless in
477 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000478
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000479 """
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000480 buf = ['', '']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000481 try:
482 while self.rawq:
483 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000484 if not self.iacseq:
485 if c == theNULL:
486 continue
487 if c == "\021":
488 continue
489 if c != IAC:
490 buf[self.sb] = buf[self.sb] + c
491 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000492 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000493 self.iacseq += c
494 elif len(self.iacseq) == 1:
Neal Norwitzc5d0dbd2006-04-09 04:00:49 +0000495 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000496 if c in (DO, DONT, WILL, WONT):
497 self.iacseq += c
498 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000499
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000500 self.iacseq = ''
501 if c == IAC:
502 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000503 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000504 if c == SB: # SB ... SE start.
505 self.sb = 1
506 self.sbdataq = ''
507 elif c == SE:
508 self.sb = 0
509 self.sbdataq = self.sbdataq + buf[1]
510 buf[1] = ''
511 if self.option_callback:
512 # Callback is supposed to look into
513 # the sbdataq
514 self.option_callback(self.sock, c, NOOPT)
515 else:
516 # We can't offer automatic processing of
517 # suboptions. Alas, we should not get any
518 # unless we did a WILL/DO before.
519 self.msg('IAC %d not recognized' % ord(c))
520 elif len(self.iacseq) == 2:
521 cmd = self.iacseq[1]
522 self.iacseq = ''
523 opt = c
524 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000525 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000526 cmd == DO and 'DO' or 'DONT', ord(opt))
527 if self.option_callback:
528 self.option_callback(self.sock, cmd, opt)
529 else:
530 self.sock.sendall(IAC + WONT + opt)
531 elif cmd in (WILL, WONT):
532 self.msg('IAC %s %d',
533 cmd == WILL and 'WILL' or 'WONT', ord(opt))
534 if self.option_callback:
535 self.option_callback(self.sock, cmd, opt)
536 else:
537 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000538 except EOFError: # raised by self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000539 self.iacseq = '' # Reset on EOF
540 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000541 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000542 self.cookedq = self.cookedq + buf[0]
543 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000544
545 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000546 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000547
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000548 Block if no data is immediately available. Raise EOFError
549 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000550
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000551 """
552 if not self.rawq:
553 self.fill_rawq()
554 if self.eof:
555 raise EOFError
556 c = self.rawq[self.irawq]
557 self.irawq = self.irawq + 1
558 if self.irawq >= len(self.rawq):
559 self.rawq = ''
560 self.irawq = 0
561 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000562
563 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000564 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000565
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000566 Block if no data is immediately available. Set self.eof when
567 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000568
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000569 """
570 if self.irawq >= len(self.rawq):
571 self.rawq = ''
572 self.irawq = 0
573 # The buffer size should be fairly small so as to avoid quadratic
574 # behavior in process_rawq() above
575 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000576 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000577 self.eof = (not buf)
578 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000579
580 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000581 """Test whether data is available on the socket."""
582 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000583
584 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000585 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000586 if sys.platform == "win32":
587 self.mt_interact()
588 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000589 while 1:
590 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
591 if self in rfd:
592 try:
593 text = self.read_eager()
594 except EOFError:
595 print '*** Connection closed by remote host ***'
596 break
597 if text:
598 sys.stdout.write(text)
599 sys.stdout.flush()
600 if sys.stdin in rfd:
601 line = sys.stdin.readline()
602 if not line:
603 break
604 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000605
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000606 def mt_interact(self):
607 """Multithreaded version of interact()."""
608 import thread
609 thread.start_new_thread(self.listener, ())
610 while 1:
611 line = sys.stdin.readline()
612 if not line:
613 break
614 self.write(line)
615
616 def listener(self):
617 """Helper for mt_interact() -- this executes in the other thread."""
618 while 1:
619 try:
620 data = self.read_eager()
621 except EOFError:
622 print '*** Connection closed by remote host ***'
623 return
624 if data:
625 sys.stdout.write(data)
626 else:
627 sys.stdout.flush()
628
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000629 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000630 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000631
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000632 The first argument is a list of regular expressions, either
633 compiled (re.RegexObject instances) or uncompiled (strings).
634 The optional second argument is a timeout, in seconds; default
635 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000636
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000637 Return a tuple of three items: the index in the list of the
638 first regular expression that matches; the match object
639 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000640
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000641 If EOF is read and no text was read, raise EOFError.
642 Otherwise, when nothing matches, return (-1, None, text) where
643 text is the text received so far (may be the empty string if a
644 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000645
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000646 If a regular expression ends with a greedy match (e.g. '.*')
647 or if more than one expression can match the same input, the
648 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000649
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000650 """
Gregory P. Smithe0c22202012-07-15 22:16:06 -0700651 if self._has_poll:
652 return self._expect_with_poll(list, timeout)
653 else:
654 return self._expect_with_select(list, timeout)
655
656 def _expect_with_poll(self, expect_list, timeout=None):
657 """Read until one from a list of a regular expressions matches.
658
659 This method uses select.poll() to implement the timeout.
660 """
661 re = None
662 expect_list = expect_list[:]
663 indices = range(len(expect_list))
664 for i in indices:
665 if not hasattr(expect_list[i], "search"):
666 if not re: import re
667 expect_list[i] = re.compile(expect_list[i])
668 call_timeout = timeout
669 if timeout is not None:
670 from time import time
671 time_start = time()
672 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. Smith9ffb1482013-12-10 18:22:03 -0800687 ready = poller.poll(None if timeout is None
688 else 1000 * call_timeout)
Gregory P. Smithe0c22202012-07-15 22:16:06 -0700689 except select.error as e:
690 if e.errno == errno.EINTR:
691 if timeout is not None:
692 elapsed = time() - time_start
693 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:
708 elapsed = time() - time_start
709 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])
Martin v. Löwisede77f52006-07-03 13:01:35 +0000732 if timeout is not None:
733 from time import time
734 time_start = time()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000735 while 1:
736 self.process_rawq()
737 for i in indices:
738 m = list[i].search(self.cookedq)
739 if m:
740 e = m.end()
741 text = self.cookedq[:e]
742 self.cookedq = self.cookedq[e:]
743 return (i, m, text)
744 if self.eof:
745 break
746 if timeout is not None:
Martin v. Löwisede77f52006-07-03 13:01:35 +0000747 elapsed = time() - time_start
748 if elapsed >= timeout:
749 break
750 s_args = ([self.fileno()], [], [], timeout-elapsed)
751 r, w, x = select.select(*s_args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000752 if not r:
753 break
754 self.fill_rawq()
755 text = self.read_very_lazy()
756 if not text and self.eof:
757 raise EOFError
758 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000759
760
761def test():
762 """Test program for telnetlib.
763
764 Usage: python telnetlib.py [-d] ... [host [port]]
765
766 Default host is localhost; default port is 23.
767
768 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000769 debuglevel = 0
770 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000771 debuglevel = debuglevel+1
772 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000773 host = 'localhost'
774 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000775 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000776 port = 0
777 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000778 portstr = sys.argv[2]
779 try:
780 port = int(portstr)
781 except ValueError:
782 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000783 tn = Telnet()
784 tn.set_debuglevel(debuglevel)
Facundo Batistab6a5c9d2007-03-29 18:22:35 +0000785 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000786 tn.interact()
787 tn.close()
788
789if __name__ == '__main__':
790 test()