blob: c8ddd972cec58bff678887dd1be4d99a19f19fe0 [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
28Bugs:
29- may hang when connection is slow in the middle of an IAC sequence
30
31To do:
32- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000033- timeout should be intrinsic to the connection object instead of an
34 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000035
36"""
37
38
39# Imported modules
Guido van Rossumccb5ec61997-12-24 22:24:19 +000040import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000041import socket
42import select
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000043
Skip Montanaro40fc1602001-03-01 04:27:19 +000044__all__ = ["Telnet"]
45
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000046# Tunable parameters
47DEBUGLEVEL = 0
48
49# Telnet protocol defaults
50TELNET_PORT = 23
51
52# Telnet protocol characters (don't change)
53IAC = chr(255) # "Interpret As Command"
54DONT = chr(254)
55DO = chr(253)
56WONT = chr(252)
57WILL = chr(251)
58theNULL = chr(0)
59
Martin v. Löwisb0162f92001-09-06 08:51:38 +000060# Telnet protocol options code (don't change)
61# These ones all come from arpa/telnet.h
62BINARY = chr(0) # 8-bit data path
63ECHO = chr(1) # echo
64RCP = chr(2) # prepare to reconnect
65SGA = chr(3) # suppress go ahead
66NAMS = chr(4) # approximate message size
67STATUS = chr(5) # give status
68TM = chr(6) # timing mark
69RCTE = chr(7) # remote controlled transmission and echo
70NAOL = chr(8) # negotiate about output line width
71NAOP = chr(9) # negotiate about output page size
72NAOCRD = chr(10) # negotiate about CR disposition
73NAOHTS = chr(11) # negotiate about horizontal tabstops
74NAOHTD = chr(12) # negotiate about horizontal tab disposition
75NAOFFD = chr(13) # negotiate about formfeed disposition
76NAOVTS = chr(14) # negotiate about vertical tab stops
77NAOVTD = chr(15) # negotiate about vertical tab disposition
78NAOLFD = chr(16) # negotiate about output LF disposition
79XASCII = chr(17) # extended ascii character set
80LOGOUT = chr(18) # force logout
81BM = chr(19) # byte macro
82DET = chr(20) # data entry terminal
83SUPDUP = chr(21) # supdup protocol
84SUPDUPOUTPUT = chr(22) # supdup output
85SNDLOC = chr(23) # send location
86TTYPE = chr(24) # terminal type
87EOR = chr(25) # end or record
88TUID = chr(26) # TACACS user identification
89OUTMRK = chr(27) # output marking
90TTYLOC = chr(28) # terminal location number
91VT3270REGIME = chr(29) # 3270 regime
92X3PAD = chr(30) # X.3 PAD
93NAWS = chr(31) # window size
94TSPEED = chr(32) # terminal speed
95LFLOW = chr(33) # remote flow control
96LINEMODE = chr(34) # Linemode option
97XDISPLOC = chr(35) # X Display Location
98OLD_ENVIRON = chr(36) # Old - Environment variables
99AUTHENTICATION = chr(37) # Authenticate
100ENCRYPT = chr(38) # Encryption option
101NEW_ENVIRON = chr(39) # New - Environment variables
102# the following ones come from
103# http://www.iana.org/assignments/telnet-options
104# Unfortunately, that document does not assign identifiers
105# to all of them, so we are making them up
106TN3270E = chr(40) # TN3270E
107XAUTH = chr(41) # XAUTH
108CHARSET = chr(42) # CHARSET
109RSP = chr(43) # Telnet Remote Serial Port
110COM_PORT_OPTION = chr(44) # Com Port Control Option
111SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
112TLS = chr(46) # Telnet Start TLS
113KERMIT = chr(47) # KERMIT
114SEND_URL = chr(48) # SEND-URL
115FORWARD_X = chr(49) # FORWARD_X
116PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
117SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
118PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
119EXOPL = chr(255) # Extended-Options-List
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000120
121class Telnet:
122
123 """Telnet interface class.
124
125 An instance of this class represents a connection to a telnet
126 server. The instance is initially not connected; the open()
127 method must be used to establish a connection. Alternatively, the
128 host name and optional port number can be passed to the
129 constructor, too.
130
131 Don't try to reopen an already connected instance.
132
133 This class has many read_*() methods. Note that some of them
134 raise EOFError when the end of the connection is read, because
135 they can return an empty string for other reasons. See the
136 individual doc strings.
137
138 read_until(expected, [timeout])
139 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000140 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000141
142 read_all()
143 Read all data until EOF; may block.
144
145 read_some()
146 Read at least one byte or EOF; may block.
147
148 read_very_eager()
149 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000150 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000151
152 read_eager()
153 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000154 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000155
156 read_lazy()
157 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000158 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000159
160 read_very_lazy()
161 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000162 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000163
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000164 set_option_negotiation_callback(callback)
165 Each time a telnet option is read on the input flow, this callback
166 (if set) is called with the following parameters :
167 callback(telnet socket, command (DO/DONT/WILL/WONT), option)
168 No other action is done afterwards by telnetlib.
169
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000170 """
171
172 def __init__(self, host=None, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000174
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000175 When called without arguments, create an unconnected instance.
176 With a hostname argument, it connects the instance; a port
177 number is optional.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000178
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000179 """
180 self.debuglevel = DEBUGLEVEL
181 self.host = host
182 self.port = port
183 self.sock = None
184 self.rawq = ''
185 self.irawq = 0
186 self.cookedq = ''
187 self.eof = 0
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000188 self.option_callback = None
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 if host:
190 self.open(host, port)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000191
192 def open(self, host, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000193 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000194
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000195 The optional second argument is the port number, which
196 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000197
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000198 Don't try to reopen an already connected instance.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000199
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 """
201 self.eof = 0
202 if not port:
203 port = TELNET_PORT
204 self.host = host
205 self.port = port
Martin v. Löwis2ad25692001-07-31 08:40:21 +0000206 msg = "getaddrinfo returns an empty list"
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000207 for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
208 af, socktype, proto, canonname, sa = res
209 try:
210 self.sock = socket.socket(af, socktype, proto)
211 self.sock.connect(sa)
212 except socket.error, msg:
213 self.sock.close()
214 self.sock = None
215 continue
216 break
Martin v. Löwisa43c2f82001-07-24 20:34:08 +0000217 if not self.sock:
Martin v. Löwis4eb59402001-07-26 13:37:33 +0000218 raise socket.error, msg
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000219
220 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000221 """Destructor -- close the connection."""
222 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000223
224 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000225 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000226
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000227 If extra arguments are present, they are substituted in the
228 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000229
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 """
231 if self.debuglevel > 0:
232 print 'Telnet(%s,%d):' % (self.host, self.port),
233 if args:
234 print msg % args
235 else:
236 print msg
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000237
238 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000239 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000240
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000242
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000243 """
244 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000245
246 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000247 """Close the connection."""
248 if self.sock:
249 self.sock.close()
250 self.sock = 0
251 self.eof = 1
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000252
253 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 """Return the socket object used internally."""
255 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000256
257 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000258 """Return the fileno() of the socket object used internally."""
259 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000260
261 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000262 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000263
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000264 Can block if the connection is blocked. May raise
265 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000266
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 """
268 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000269 buffer = buffer.replace(IAC, IAC+IAC)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000270 self.msg("send %s", `buffer`)
271 self.sock.send(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000272
273 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000274 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000275
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 When no match is found, return whatever is available instead,
277 possibly the empty string. Raise EOFError if the connection
278 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000279
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000280 """
281 n = len(match)
282 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000283 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000284 if i >= 0:
285 i = i+n
286 buf = self.cookedq[:i]
287 self.cookedq = self.cookedq[i:]
288 return buf
289 s_reply = ([self], [], [])
290 s_args = s_reply
291 if timeout is not None:
292 s_args = s_args + (timeout,)
293 while not self.eof and apply(select.select, s_args) == s_reply:
294 i = max(0, len(self.cookedq)-n)
295 self.fill_rawq()
296 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000297 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000298 if i >= 0:
299 i = i+n
300 buf = self.cookedq[:i]
301 self.cookedq = self.cookedq[i:]
302 return buf
303 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000304
305 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000306 """Read all data until EOF; block until connection closed."""
307 self.process_rawq()
308 while not self.eof:
309 self.fill_rawq()
310 self.process_rawq()
311 buf = self.cookedq
312 self.cookedq = ''
313 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000314
315 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000316 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000317
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000318 Return '' if EOF is hit. Block if no data is immediately
319 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000320
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000321 """
322 self.process_rawq()
323 while not self.cookedq and not self.eof:
324 self.fill_rawq()
325 self.process_rawq()
326 buf = self.cookedq
327 self.cookedq = ''
328 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000329
330 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000331 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000332
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000333 Raise EOFError if connection closed and no cooked data
334 available. Return '' if no cooked data available otherwise.
335 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000336
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000337 """
338 self.process_rawq()
339 while not self.eof and self.sock_avail():
340 self.fill_rawq()
341 self.process_rawq()
342 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000343
344 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000345 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000346
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 Raise EOFError if connection closed and no cooked data
348 available. Return '' if no cooked data available otherwise.
349 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000350
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 """
352 self.process_rawq()
353 while not self.cookedq and not self.eof and self.sock_avail():
354 self.fill_rawq()
355 self.process_rawq()
356 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000357
358 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000360
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 Raise EOFError if connection closed and no data available.
362 Return '' if no cooked data available otherwise. Don't block
363 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000364
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000365 """
366 self.process_rawq()
367 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000368
369 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000370 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000371
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000372 Raise EOFError if connection closed and no data available.
373 Return '' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000374
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000375 """
376 buf = self.cookedq
377 self.cookedq = ''
378 if not buf and self.eof and not self.rawq:
379 raise EOFError, 'telnet connection closed'
380 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000381
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000382 def set_option_negotiation_callback(self, callback):
383 """Provide a callback function called after each receipt of a telnet option."""
384 self.option_callback = callback
385
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000386 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000388
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 Set self.eof when connection is closed. Don't block unless in
390 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000391
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000392 """
393 buf = ''
394 try:
395 while self.rawq:
396 c = self.rawq_getchar()
397 if c == theNULL:
398 continue
399 if c == "\021":
400 continue
401 if c != IAC:
402 buf = buf + c
403 continue
404 c = self.rawq_getchar()
405 if c == IAC:
406 buf = buf + c
407 elif c in (DO, DONT):
408 opt = self.rawq_getchar()
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000409 self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(opt))
410 if self.option_callback:
411 self.option_callback(self.sock, c, opt)
412 else:
413 self.sock.send(IAC + WONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000414 elif c in (WILL, WONT):
415 opt = self.rawq_getchar()
416 self.msg('IAC %s %d',
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000417 c == WILL and 'WILL' or 'WONT', ord(opt))
418 if self.option_callback:
419 self.option_callback(self.sock, c, opt)
420 else:
421 self.sock.send(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 else:
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000423 self.msg('IAC %d not recognized' % ord(opt))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000424 except EOFError: # raised by self.rawq_getchar()
425 pass
426 self.cookedq = self.cookedq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000427
428 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000429 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000430
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000431 Block if no data is immediately available. Raise EOFError
432 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000433
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000434 """
435 if not self.rawq:
436 self.fill_rawq()
437 if self.eof:
438 raise EOFError
439 c = self.rawq[self.irawq]
440 self.irawq = self.irawq + 1
441 if self.irawq >= len(self.rawq):
442 self.rawq = ''
443 self.irawq = 0
444 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000445
446 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000447 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000448
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000449 Block if no data is immediately available. Set self.eof when
450 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000451
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000452 """
453 if self.irawq >= len(self.rawq):
454 self.rawq = ''
455 self.irawq = 0
456 # The buffer size should be fairly small so as to avoid quadratic
457 # behavior in process_rawq() above
458 buf = self.sock.recv(50)
459 self.msg("recv %s", `buf`)
460 self.eof = (not buf)
461 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000462
463 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000464 """Test whether data is available on the socket."""
465 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000466
467 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000468 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000469 if sys.platform == "win32":
470 self.mt_interact()
471 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000472 while 1:
473 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
474 if self in rfd:
475 try:
476 text = self.read_eager()
477 except EOFError:
478 print '*** Connection closed by remote host ***'
479 break
480 if text:
481 sys.stdout.write(text)
482 sys.stdout.flush()
483 if sys.stdin in rfd:
484 line = sys.stdin.readline()
485 if not line:
486 break
487 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000488
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000489 def mt_interact(self):
490 """Multithreaded version of interact()."""
491 import thread
492 thread.start_new_thread(self.listener, ())
493 while 1:
494 line = sys.stdin.readline()
495 if not line:
496 break
497 self.write(line)
498
499 def listener(self):
500 """Helper for mt_interact() -- this executes in the other thread."""
501 while 1:
502 try:
503 data = self.read_eager()
504 except EOFError:
505 print '*** Connection closed by remote host ***'
506 return
507 if data:
508 sys.stdout.write(data)
509 else:
510 sys.stdout.flush()
511
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000512 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000513 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000514
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000515 The first argument is a list of regular expressions, either
516 compiled (re.RegexObject instances) or uncompiled (strings).
517 The optional second argument is a timeout, in seconds; default
518 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000519
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000520 Return a tuple of three items: the index in the list of the
521 first regular expression that matches; the match object
522 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000523
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000524 If EOF is read and no text was read, raise EOFError.
525 Otherwise, when nothing matches, return (-1, None, text) where
526 text is the text received so far (may be the empty string if a
527 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000528
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000529 If a regular expression ends with a greedy match (e.g. '.*')
530 or if more than one expression can match the same input, the
531 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000532
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000533 """
534 re = None
535 list = list[:]
536 indices = range(len(list))
537 for i in indices:
538 if not hasattr(list[i], "search"):
539 if not re: import re
540 list[i] = re.compile(list[i])
541 while 1:
542 self.process_rawq()
543 for i in indices:
544 m = list[i].search(self.cookedq)
545 if m:
546 e = m.end()
547 text = self.cookedq[:e]
548 self.cookedq = self.cookedq[e:]
549 return (i, m, text)
550 if self.eof:
551 break
552 if timeout is not None:
553 r, w, x = select.select([self.fileno()], [], [], timeout)
554 if not r:
555 break
556 self.fill_rawq()
557 text = self.read_very_lazy()
558 if not text and self.eof:
559 raise EOFError
560 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000561
562
563def test():
564 """Test program for telnetlib.
565
566 Usage: python telnetlib.py [-d] ... [host [port]]
567
568 Default host is localhost; default port is 23.
569
570 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000571 debuglevel = 0
572 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000573 debuglevel = debuglevel+1
574 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000575 host = 'localhost'
576 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000577 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000578 port = 0
579 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000580 portstr = sys.argv[2]
581 try:
582 port = int(portstr)
583 except ValueError:
584 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000585 tn = Telnet()
586 tn.set_debuglevel(debuglevel)
587 tn.open(host, port)
588 tn.interact()
589 tn.close()
590
591if __name__ == '__main__':
592 test()