blob: 231618af2ae71e1b6057c475946fab3aff6b37db [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
44# 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)
57
58
59class Telnet:
60
61 """Telnet interface class.
62
63 An instance of this class represents a connection to a telnet
64 server. The instance is initially not connected; the open()
65 method must be used to establish a connection. Alternatively, the
66 host name and optional port number can be passed to the
67 constructor, too.
68
69 Don't try to reopen an already connected instance.
70
71 This class has many read_*() methods. Note that some of them
72 raise EOFError when the end of the connection is read, because
73 they can return an empty string for other reasons. See the
74 individual doc strings.
75
76 read_until(expected, [timeout])
77 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000078 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000079
80 read_all()
81 Read all data until EOF; may block.
82
83 read_some()
84 Read at least one byte or EOF; may block.
85
86 read_very_eager()
87 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000088 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000089
90 read_eager()
91 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000092 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000093
94 read_lazy()
95 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +000096 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000097
98 read_very_lazy()
99 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000100 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000101
102 """
103
104 def __init__(self, host=None, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000105 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000106
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000107 When called without arguments, create an unconnected instance.
108 With a hostname argument, it connects the instance; a port
109 number is optional.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000110
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000111 """
112 self.debuglevel = DEBUGLEVEL
113 self.host = host
114 self.port = port
115 self.sock = None
116 self.rawq = ''
117 self.irawq = 0
118 self.cookedq = ''
119 self.eof = 0
120 if host:
121 self.open(host, port)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000122
123 def open(self, host, port=0):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000124 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000125
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000126 The optional second argument is the port number, which
127 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000128
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000129 Don't try to reopen an already connected instance.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000130
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000131 """
132 self.eof = 0
133 if not port:
134 port = TELNET_PORT
135 self.host = host
136 self.port = port
137 self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
138 self.sock.connect((self.host, self.port))
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000139
140 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000141 """Destructor -- close the connection."""
142 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000143
144 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000145 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000146
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000147 If extra arguments are present, they are substituted in the
148 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000149
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000150 """
151 if self.debuglevel > 0:
152 print 'Telnet(%s,%d):' % (self.host, self.port),
153 if args:
154 print msg % args
155 else:
156 print msg
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000157
158 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000159 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000160
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000161 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000162
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 """
164 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000165
166 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000167 """Close the connection."""
168 if self.sock:
169 self.sock.close()
170 self.sock = 0
171 self.eof = 1
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000172
173 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000174 """Return the socket object used internally."""
175 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000176
177 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000178 """Return the fileno() of the socket object used internally."""
179 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000180
181 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000182 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000183
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000184 Can block if the connection is blocked. May raise
185 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000186
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000187 """
188 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000189 buffer = buffer.replace(IAC, IAC+IAC)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000190 self.msg("send %s", `buffer`)
191 self.sock.send(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000192
193 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000195
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000196 When no match is found, return whatever is available instead,
197 possibly the empty string. Raise EOFError if the connection
198 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000199
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000200 """
201 n = len(match)
202 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000203 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000204 if i >= 0:
205 i = i+n
206 buf = self.cookedq[:i]
207 self.cookedq = self.cookedq[i:]
208 return buf
209 s_reply = ([self], [], [])
210 s_args = s_reply
211 if timeout is not None:
212 s_args = s_args + (timeout,)
213 while not self.eof and apply(select.select, s_args) == s_reply:
214 i = max(0, len(self.cookedq)-n)
215 self.fill_rawq()
216 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000217 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000218 if i >= 0:
219 i = i+n
220 buf = self.cookedq[:i]
221 self.cookedq = self.cookedq[i:]
222 return buf
223 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000224
225 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 """Read all data until EOF; block until connection closed."""
227 self.process_rawq()
228 while not self.eof:
229 self.fill_rawq()
230 self.process_rawq()
231 buf = self.cookedq
232 self.cookedq = ''
233 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000234
235 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000236 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000237
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000238 Return '' if EOF is hit. Block if no data is immediately
239 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000240
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000241 """
242 self.process_rawq()
243 while not self.cookedq and not self.eof:
244 self.fill_rawq()
245 self.process_rawq()
246 buf = self.cookedq
247 self.cookedq = ''
248 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000249
250 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000251 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000252
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000253 Raise EOFError if connection closed and no cooked data
254 available. Return '' if no cooked data available otherwise.
255 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000256
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000257 """
258 self.process_rawq()
259 while not self.eof and self.sock_avail():
260 self.fill_rawq()
261 self.process_rawq()
262 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000263
264 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000265 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000266
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 Raise EOFError if connection closed and no cooked data
268 available. Return '' if no cooked data available otherwise.
269 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000270
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000271 """
272 self.process_rawq()
273 while not self.cookedq and not self.eof and self.sock_avail():
274 self.fill_rawq()
275 self.process_rawq()
276 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000277
278 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000279 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000280
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000281 Raise EOFError if connection closed and no data available.
282 Return '' if no cooked data available otherwise. Don't block
283 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000284
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 """
286 self.process_rawq()
287 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000288
289 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000290 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000291
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000292 Raise EOFError if connection closed and no data available.
293 Return '' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000294
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000295 """
296 buf = self.cookedq
297 self.cookedq = ''
298 if not buf and self.eof and not self.rawq:
299 raise EOFError, 'telnet connection closed'
300 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000301
302 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000303 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000304
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000305 Set self.eof when connection is closed. Don't block unless in
306 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000307
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000308 """
309 buf = ''
310 try:
311 while self.rawq:
312 c = self.rawq_getchar()
313 if c == theNULL:
314 continue
315 if c == "\021":
316 continue
317 if c != IAC:
318 buf = buf + c
319 continue
320 c = self.rawq_getchar()
321 if c == IAC:
322 buf = buf + c
323 elif c in (DO, DONT):
324 opt = self.rawq_getchar()
325 self.msg('IAC %s %d', c == DO and 'DO' or 'DONT', ord(c))
326 self.sock.send(IAC + WONT + opt)
327 elif c in (WILL, WONT):
328 opt = self.rawq_getchar()
329 self.msg('IAC %s %d',
330 c == WILL and 'WILL' or 'WONT', ord(c))
Guido van Rossum823eb4b2000-05-02 14:32:11 +0000331 self.sock.send(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 else:
333 self.msg('IAC %s not recognized' % `c`)
334 except EOFError: # raised by self.rawq_getchar()
335 pass
336 self.cookedq = self.cookedq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000337
338 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000339 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000340
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000341 Block if no data is immediately available. Raise EOFError
342 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000343
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 """
345 if not self.rawq:
346 self.fill_rawq()
347 if self.eof:
348 raise EOFError
349 c = self.rawq[self.irawq]
350 self.irawq = self.irawq + 1
351 if self.irawq >= len(self.rawq):
352 self.rawq = ''
353 self.irawq = 0
354 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000355
356 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000358
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 Block if no data is immediately available. Set self.eof when
360 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000361
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000362 """
363 if self.irawq >= len(self.rawq):
364 self.rawq = ''
365 self.irawq = 0
366 # The buffer size should be fairly small so as to avoid quadratic
367 # behavior in process_rawq() above
368 buf = self.sock.recv(50)
369 self.msg("recv %s", `buf`)
370 self.eof = (not buf)
371 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000372
373 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000374 """Test whether data is available on the socket."""
375 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000376
377 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000378 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000379 if sys.platform == "win32":
380 self.mt_interact()
381 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000382 while 1:
383 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
384 if self in rfd:
385 try:
386 text = self.read_eager()
387 except EOFError:
388 print '*** Connection closed by remote host ***'
389 break
390 if text:
391 sys.stdout.write(text)
392 sys.stdout.flush()
393 if sys.stdin in rfd:
394 line = sys.stdin.readline()
395 if not line:
396 break
397 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000398
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000399 def mt_interact(self):
400 """Multithreaded version of interact()."""
401 import thread
402 thread.start_new_thread(self.listener, ())
403 while 1:
404 line = sys.stdin.readline()
405 if not line:
406 break
407 self.write(line)
408
409 def listener(self):
410 """Helper for mt_interact() -- this executes in the other thread."""
411 while 1:
412 try:
413 data = self.read_eager()
414 except EOFError:
415 print '*** Connection closed by remote host ***'
416 return
417 if data:
418 sys.stdout.write(data)
419 else:
420 sys.stdout.flush()
421
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000422 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000423 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000424
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 The first argument is a list of regular expressions, either
426 compiled (re.RegexObject instances) or uncompiled (strings).
427 The optional second argument is a timeout, in seconds; default
428 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000429
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 Return a tuple of three items: the index in the list of the
431 first regular expression that matches; the match object
432 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000433
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000434 If EOF is read and no text was read, raise EOFError.
435 Otherwise, when nothing matches, return (-1, None, text) where
436 text is the text received so far (may be the empty string if a
437 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000438
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000439 If a regular expression ends with a greedy match (e.g. '.*')
440 or if more than one expression can match the same input, the
441 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000442
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000443 """
444 re = None
445 list = list[:]
446 indices = range(len(list))
447 for i in indices:
448 if not hasattr(list[i], "search"):
449 if not re: import re
450 list[i] = re.compile(list[i])
451 while 1:
452 self.process_rawq()
453 for i in indices:
454 m = list[i].search(self.cookedq)
455 if m:
456 e = m.end()
457 text = self.cookedq[:e]
458 self.cookedq = self.cookedq[e:]
459 return (i, m, text)
460 if self.eof:
461 break
462 if timeout is not None:
463 r, w, x = select.select([self.fileno()], [], [], timeout)
464 if not r:
465 break
466 self.fill_rawq()
467 text = self.read_very_lazy()
468 if not text and self.eof:
469 raise EOFError
470 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000471
472
473def test():
474 """Test program for telnetlib.
475
476 Usage: python telnetlib.py [-d] ... [host [port]]
477
478 Default host is localhost; default port is 23.
479
480 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000481 debuglevel = 0
482 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000483 debuglevel = debuglevel+1
484 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000485 host = 'localhost'
486 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000488 port = 0
489 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000490 portstr = sys.argv[2]
491 try:
492 port = int(portstr)
493 except ValueError:
494 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000495 tn = Telnet()
496 tn.set_debuglevel(debuglevel)
497 tn.open(host, port)
498 tn.interact()
499 tn.close()
500
501if __name__ == '__main__':
502 test()