blob: f073050b81747f84a51a8ad3dc48d8b339a105b9 [file] [log] [blame]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +00001"""TELNET client class.
2
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
Guido van Rossumccb5ec61997-12-24 22:24:19 +000037import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000038import socket
39import select
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000040
Skip Montanaro40fc1602001-03-01 04:27:19 +000041__all__ = ["Telnet"]
42
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000043# Tunable parameters
44DEBUGLEVEL = 0
45
46# Telnet protocol defaults
47TELNET_PORT = 23
48
49# Telnet protocol characters (don't change)
50IAC = chr(255) # "Interpret As Command"
51DONT = chr(254)
52DO = chr(253)
53WONT = chr(252)
54WILL = chr(251)
55theNULL = chr(0)
Martin v. Löwis574deae2002-11-04 17:34:07 +000056
57SE = chr(240) # Subnegotiation End
58NOP = chr(241) # No Operation
59DM = chr(242) # Data Mark
60BRK = chr(243) # Break
61IP = chr(244) # Interrupt process
62AO = chr(245) # Abort output
63AYT = chr(246) # Are You There
64EC = chr(247) # Erase Character
65EL = chr(248) # Erase Line
66GA = chr(249) # Go Ahead
67SB = chr(250) # Subnegotiation Begin
68
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000069
Martin v. Löwisb0162f92001-09-06 08:51:38 +000070# Telnet protocol options code (don't change)
71# These ones all come from arpa/telnet.h
72BINARY = chr(0) # 8-bit data path
73ECHO = chr(1) # echo
74RCP = chr(2) # prepare to reconnect
75SGA = chr(3) # suppress go ahead
76NAMS = chr(4) # approximate message size
77STATUS = chr(5) # give status
78TM = chr(6) # timing mark
79RCTE = chr(7) # remote controlled transmission and echo
80NAOL = chr(8) # negotiate about output line width
81NAOP = chr(9) # negotiate about output page size
82NAOCRD = chr(10) # negotiate about CR disposition
83NAOHTS = chr(11) # negotiate about horizontal tabstops
84NAOHTD = chr(12) # negotiate about horizontal tab disposition
85NAOFFD = chr(13) # negotiate about formfeed disposition
86NAOVTS = chr(14) # negotiate about vertical tab stops
87NAOVTD = chr(15) # negotiate about vertical tab disposition
88NAOLFD = chr(16) # negotiate about output LF disposition
89XASCII = chr(17) # extended ascii character set
90LOGOUT = chr(18) # force logout
91BM = chr(19) # byte macro
92DET = chr(20) # data entry terminal
93SUPDUP = chr(21) # supdup protocol
94SUPDUPOUTPUT = chr(22) # supdup output
95SNDLOC = chr(23) # send location
96TTYPE = chr(24) # terminal type
97EOR = chr(25) # end or record
98TUID = chr(26) # TACACS user identification
99OUTMRK = chr(27) # output marking
100TTYLOC = chr(28) # terminal location number
101VT3270REGIME = chr(29) # 3270 regime
102X3PAD = chr(30) # X.3 PAD
103NAWS = chr(31) # window size
104TSPEED = chr(32) # terminal speed
105LFLOW = chr(33) # remote flow control
106LINEMODE = chr(34) # Linemode option
107XDISPLOC = chr(35) # X Display Location
108OLD_ENVIRON = chr(36) # Old - Environment variables
109AUTHENTICATION = chr(37) # Authenticate
110ENCRYPT = chr(38) # Encryption option
111NEW_ENVIRON = chr(39) # New - Environment variables
112# the following ones come from
113# http://www.iana.org/assignments/telnet-options
114# Unfortunately, that document does not assign identifiers
115# to all of them, so we are making them up
116TN3270E = chr(40) # TN3270E
117XAUTH = chr(41) # XAUTH
118CHARSET = chr(42) # CHARSET
119RSP = chr(43) # Telnet Remote Serial Port
120COM_PORT_OPTION = chr(44) # Com Port Control Option
121SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
122TLS = chr(46) # Telnet Start TLS
123KERMIT = chr(47) # KERMIT
124SEND_URL = chr(48) # SEND-URL
125FORWARD_X = chr(49) # FORWARD_X
126PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
127SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
128PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
129EXOPL = chr(255) # Extended-Options-List
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000130NOOPT = chr(0)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000131
132class Telnet:
133
134 """Telnet interface class.
135
136 An instance of this class represents a connection to a telnet
137 server. The instance is initially not connected; the open()
138 method must be used to establish a connection. Alternatively, the
139 host name and optional port number can be passed to the
140 constructor, too.
141
142 Don't try to reopen an already connected instance.
143
144 This class has many read_*() methods. Note that some of them
145 raise EOFError when the end of the connection is read, because
146 they can return an empty string for other reasons. See the
147 individual doc strings.
148
149 read_until(expected, [timeout])
150 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000151 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000152
153 read_all()
154 Read all data until EOF; may block.
155
156 read_some()
157 Read at least one byte or EOF; may block.
158
159 read_very_eager()
160 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000162
163 read_eager()
164 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000165 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000166
167 read_lazy()
168 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000169 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000170
171 read_very_lazy()
172 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000174
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000175 read_sb_data()
176 Reads available data between SB ... SE sequence. Don't block.
177
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000178 set_option_negotiation_callback(callback)
179 Each time a telnet option is read on the input flow, this callback
180 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000181 callback(telnet socket, command, option)
182 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000183 No other action is done afterwards by telnetlib.
184
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000185 """
186
187 def __init__(self, host=None, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000188 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000189
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 When called without arguments, create an unconnected instance.
191 With a hostname argument, it connects the instance; a port
192 number is optional.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000193
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """
195 self.debuglevel = DEBUGLEVEL
196 self.host = host
197 self.port = port
198 self.sock = None
199 self.rawq = ''
200 self.irawq = 0
201 self.cookedq = ''
202 self.eof = 0
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000203 self.iacseq = '' # Buffer for IAC sequence.
204 self.sb = 0 # flag for SB and SE sequence.
205 self.sbdataq = ''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000206 self.option_callback = None
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000207 if host is not None:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000208 self.open(host, port)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000209
210 def open(self, host, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000211 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000212
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 The optional second argument is the port number, which
214 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000215
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000216 Don't try to reopen an already connected instance.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000217
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 """
219 self.eof = 0
220 if not port:
221 port = TELNET_PORT
222 self.host = host
223 self.port = port
Martin v. Löwis2ad25692001-07-31 08:40:21 +0000224 msg = "getaddrinfo returns an empty list"
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000225 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
226 af, socktype, proto, canonname, sa = res
227 try:
228 self.sock = socket.socket(af, socktype, proto)
229 self.sock.connect(sa)
230 except socket.error, msg:
Martin v. Löwis322c0d12001-10-07 08:53:32 +0000231 if self.sock:
232 self.sock.close()
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000233 self.sock = None
234 continue
235 break
Martin v. Löwisa43c2f82001-07-24 20:34:08 +0000236 if not self.sock:
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000237 raise socket.error, msg
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000238
239 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 """Destructor -- close the connection."""
241 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000242
243 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000244 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000245
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 If extra arguments are present, they are substituted in the
247 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000248
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000249 """
250 if self.debuglevel > 0:
251 print 'Telnet(%s,%d):' % (self.host, self.port),
252 if args:
253 print msg % args
254 else:
255 print msg
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000256
257 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000258 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000259
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000260 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000261
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000262 """
263 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000264
265 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000266 """Close the connection."""
267 if self.sock:
268 self.sock.close()
269 self.sock = 0
270 self.eof = 1
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000271 self.iacseq = ''
272 self.sb = 0
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000273
274 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000275 """Return the socket object used internally."""
276 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000277
278 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 """Return the fileno() of the socket object used internally."""
280 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000281
282 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000284
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 Can block if the connection is blocked. May raise
286 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000287
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000288 """
289 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000290 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000291 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000292 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000293
294 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000296
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000297 When no match is found, return whatever is available instead,
298 possibly the empty string. Raise EOFError if the connection
299 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000300
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000301 """
302 n = len(match)
303 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000304 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000305 if i >= 0:
306 i = i+n
307 buf = self.cookedq[:i]
308 self.cookedq = self.cookedq[i:]
309 return buf
310 s_reply = ([self], [], [])
311 s_args = s_reply
312 if timeout is not None:
313 s_args = s_args + (timeout,)
Guido van Rossum68468eb2003-02-27 20:14:51 +0000314 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000315 i = max(0, len(self.cookedq)-n)
316 self.fill_rawq()
317 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000318 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000319 if i >= 0:
320 i = i+n
321 buf = self.cookedq[:i]
322 self.cookedq = self.cookedq[i:]
323 return buf
324 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000325
326 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000327 """Read all data until EOF; block until connection closed."""
328 self.process_rawq()
329 while not self.eof:
330 self.fill_rawq()
331 self.process_rawq()
332 buf = self.cookedq
333 self.cookedq = ''
334 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000335
336 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000337 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000338
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000339 Return '' if EOF is hit. Block if no data is immediately
340 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000341
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000342 """
343 self.process_rawq()
344 while not self.cookedq and not self.eof:
345 self.fill_rawq()
346 self.process_rawq()
347 buf = self.cookedq
348 self.cookedq = ''
349 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000350
351 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000352 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000353
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000354 Raise EOFError if connection closed and no cooked data
355 available. Return '' if no cooked data available otherwise.
356 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000357
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000358 """
359 self.process_rawq()
360 while not self.eof and self.sock_avail():
361 self.fill_rawq()
362 self.process_rawq()
363 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000364
365 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000366 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000367
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000368 Raise EOFError if connection closed and no cooked data
369 available. Return '' if no cooked data available otherwise.
370 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000371
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000372 """
373 self.process_rawq()
374 while not self.cookedq and not self.eof and self.sock_avail():
375 self.fill_rawq()
376 self.process_rawq()
377 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000378
379 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000380 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000381
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000382 Raise EOFError if connection closed and no data available.
383 Return '' if no cooked data available otherwise. Don't block
384 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000385
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000386 """
387 self.process_rawq()
388 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000389
390 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000392
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000393 Raise EOFError if connection closed and no data available.
394 Return '' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000395
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 """
397 buf = self.cookedq
398 self.cookedq = ''
399 if not buf and self.eof and not self.rawq:
400 raise EOFError, 'telnet connection closed'
401 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000402
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000403 def read_sb_data(self):
404 """Return any data available in the SB ... SE queue.
405
Tim Peters230a60c2002-11-09 05:08:07 +0000406 Return '' if no SB ... SE available. Should only be called
407 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000408 found, old unread SB data will be discarded. Don't block.
409
410 """
411 buf = self.sbdataq
412 self.sbdataq = ''
413 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000414
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000415 def set_option_negotiation_callback(self, callback):
416 """Provide a callback function called after each receipt of a telnet option."""
417 self.option_callback = callback
418
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000419 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000421
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 Set self.eof when connection is closed. Don't block unless in
423 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000424
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 """
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000426 buf = ['', '']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000427 try:
428 while self.rawq:
429 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000430 if not self.iacseq:
431 if c == theNULL:
432 continue
433 if c == "\021":
434 continue
435 if c != IAC:
436 buf[self.sb] = buf[self.sb] + c
437 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000438 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000439 self.iacseq += c
440 elif len(self.iacseq) == 1:
441 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
442 if c in (DO, DONT, WILL, WONT):
443 self.iacseq += c
444 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000445
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000446 self.iacseq = ''
447 if c == IAC:
448 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000449 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000450 if c == SB: # SB ... SE start.
451 self.sb = 1
452 self.sbdataq = ''
453 elif c == SE:
454 self.sb = 0
455 self.sbdataq = self.sbdataq + buf[1]
456 buf[1] = ''
457 if self.option_callback:
458 # Callback is supposed to look into
459 # the sbdataq
460 self.option_callback(self.sock, c, NOOPT)
461 else:
462 # We can't offer automatic processing of
463 # suboptions. Alas, we should not get any
464 # unless we did a WILL/DO before.
465 self.msg('IAC %d not recognized' % ord(c))
466 elif len(self.iacseq) == 2:
467 cmd = self.iacseq[1]
468 self.iacseq = ''
469 opt = c
470 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000471 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000472 cmd == DO and 'DO' or 'DONT', ord(opt))
473 if self.option_callback:
474 self.option_callback(self.sock, cmd, opt)
475 else:
476 self.sock.sendall(IAC + WONT + opt)
477 elif cmd in (WILL, WONT):
478 self.msg('IAC %s %d',
479 cmd == WILL and 'WILL' or 'WONT', ord(opt))
480 if self.option_callback:
481 self.option_callback(self.sock, cmd, opt)
482 else:
483 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000484 except EOFError: # raised by self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000485 self.iacseq = '' # Reset on EOF
486 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000488 self.cookedq = self.cookedq + buf[0]
489 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000490
491 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000493
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000494 Block if no data is immediately available. Raise EOFError
495 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000496
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000497 """
498 if not self.rawq:
499 self.fill_rawq()
500 if self.eof:
501 raise EOFError
502 c = self.rawq[self.irawq]
503 self.irawq = self.irawq + 1
504 if self.irawq >= len(self.rawq):
505 self.rawq = ''
506 self.irawq = 0
507 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000508
509 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000510 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000511
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000512 Block if no data is immediately available. Set self.eof when
513 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000514
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000515 """
516 if self.irawq >= len(self.rawq):
517 self.rawq = ''
518 self.irawq = 0
519 # The buffer size should be fairly small so as to avoid quadratic
520 # behavior in process_rawq() above
521 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000522 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000523 self.eof = (not buf)
524 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000525
526 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000527 """Test whether data is available on the socket."""
528 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000529
530 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000531 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000532 if sys.platform == "win32":
533 self.mt_interact()
534 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000535 while 1:
536 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
537 if self in rfd:
538 try:
539 text = self.read_eager()
540 except EOFError:
541 print '*** Connection closed by remote host ***'
542 break
543 if text:
544 sys.stdout.write(text)
545 sys.stdout.flush()
546 if sys.stdin in rfd:
547 line = sys.stdin.readline()
548 if not line:
549 break
550 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000551
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000552 def mt_interact(self):
553 """Multithreaded version of interact()."""
554 import thread
555 thread.start_new_thread(self.listener, ())
556 while 1:
557 line = sys.stdin.readline()
558 if not line:
559 break
560 self.write(line)
561
562 def listener(self):
563 """Helper for mt_interact() -- this executes in the other thread."""
564 while 1:
565 try:
566 data = self.read_eager()
567 except EOFError:
568 print '*** Connection closed by remote host ***'
569 return
570 if data:
571 sys.stdout.write(data)
572 else:
573 sys.stdout.flush()
574
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000575 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000576 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000577
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000578 The first argument is a list of regular expressions, either
579 compiled (re.RegexObject instances) or uncompiled (strings).
580 The optional second argument is a timeout, in seconds; default
581 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000582
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000583 Return a tuple of three items: the index in the list of the
584 first regular expression that matches; the match object
585 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000586
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 If EOF is read and no text was read, raise EOFError.
588 Otherwise, when nothing matches, return (-1, None, text) where
589 text is the text received so far (may be the empty string if a
590 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000591
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000592 If a regular expression ends with a greedy match (e.g. '.*')
593 or if more than one expression can match the same input, the
594 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000595
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000596 """
597 re = None
598 list = list[:]
599 indices = range(len(list))
600 for i in indices:
601 if not hasattr(list[i], "search"):
602 if not re: import re
603 list[i] = re.compile(list[i])
604 while 1:
605 self.process_rawq()
606 for i in indices:
607 m = list[i].search(self.cookedq)
608 if m:
609 e = m.end()
610 text = self.cookedq[:e]
611 self.cookedq = self.cookedq[e:]
612 return (i, m, text)
613 if self.eof:
614 break
615 if timeout is not None:
616 r, w, x = select.select([self.fileno()], [], [], timeout)
617 if not r:
618 break
619 self.fill_rawq()
620 text = self.read_very_lazy()
621 if not text and self.eof:
622 raise EOFError
623 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000624
625
626def test():
627 """Test program for telnetlib.
628
629 Usage: python telnetlib.py [-d] ... [host [port]]
630
631 Default host is localhost; default port is 23.
632
633 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000634 debuglevel = 0
635 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000636 debuglevel = debuglevel+1
637 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000638 host = 'localhost'
639 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000640 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000641 port = 0
642 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000643 portstr = sys.argv[2]
644 try:
645 port = int(portstr)
646 except ValueError:
647 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000648 tn = Telnet()
649 tn.set_debuglevel(debuglevel)
650 tn.open(host, port)
651 tn.interact()
652 tn.close()
653
654if __name__ == '__main__':
655 test()