blob: 11e1a654b9b0edaad6a868552a4d6dfcdf4c920a [file] [log] [blame]
Hye-Shik Change029da02005-09-07 07:40:05 +00001r"""TELNET client class.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +00002
3Based on RFC 854: TELNET Protocol Specification, by J. Postel and
4J. Reynolds
5
6Example:
7
8>>> from telnetlib import Telnet
9>>> tn = Telnet('www.python.org', 79) # connect to finger port
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000010>>> tn.write(b'guido\r\n')
Guido van Rossum7131f842007-02-09 20:13:25 +000011>>> print(tn.read_all())
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000012Login Name TTY Idle When Where
13guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
Tim Petersb90f89a2001-01-15 03:26:36 +000014
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000015>>>
16
17Note that read_all() won't read until eof -- it just reads some data
18-- but it guarantees to read at least one byte unless EOF is hit.
19
20It is possible to pass a Telnet object to select.select() in order to
21wait until more data is available. Note that in this case,
Benjamin Peterson3de7fb82008-10-15 20:54:24 +000022read_eager() may return b'' even if there was data on the socket,
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000023because the protocol negotiation may have eaten the data. This is why
24EOFError is needed in some cases to distinguish between "no data" and
25"connection closed" (since the socket also appears ready for reading
26when it is closed).
27
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000028To do:
29- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000030- timeout should be intrinsic to the connection object instead of an
31 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000032
33"""
34
35
36# Imported modules
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)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000050IAC = bytes([255]) # "Interpret As Command"
51DONT = bytes([254])
52DO = bytes([253])
53WONT = bytes([252])
54WILL = bytes([251])
55theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000056
Jack Diederich1c8f38c2009-04-10 05:33:26 +000057SE = bytes([240]) # Subnegotiation End
58NOP = bytes([241]) # No Operation
59DM = bytes([242]) # Data Mark
60BRK = bytes([243]) # Break
61IP = bytes([244]) # Interrupt process
62AO = bytes([245]) # Abort output
63AYT = bytes([246]) # Are You There
64EC = bytes([247]) # Erase Character
65EL = bytes([248]) # Erase Line
66GA = bytes([249]) # Go Ahead
67SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000068
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
Jack Diederich1c8f38c2009-04-10 05:33:26 +000072BINARY = bytes([0]) # 8-bit data path
73ECHO = bytes([1]) # echo
74RCP = bytes([2]) # prepare to reconnect
75SGA = bytes([3]) # suppress go ahead
76NAMS = bytes([4]) # approximate message size
77STATUS = bytes([5]) # give status
78TM = bytes([6]) # timing mark
79RCTE = bytes([7]) # remote controlled transmission and echo
80NAOL = bytes([8]) # negotiate about output line width
81NAOP = bytes([9]) # negotiate about output page size
82NAOCRD = bytes([10]) # negotiate about CR disposition
83NAOHTS = bytes([11]) # negotiate about horizontal tabstops
84NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
85NAOFFD = bytes([13]) # negotiate about formfeed disposition
86NAOVTS = bytes([14]) # negotiate about vertical tab stops
87NAOVTD = bytes([15]) # negotiate about vertical tab disposition
88NAOLFD = bytes([16]) # negotiate about output LF disposition
89XASCII = bytes([17]) # extended ascii character set
90LOGOUT = bytes([18]) # force logout
91BM = bytes([19]) # byte macro
92DET = bytes([20]) # data entry terminal
93SUPDUP = bytes([21]) # supdup protocol
94SUPDUPOUTPUT = bytes([22]) # supdup output
95SNDLOC = bytes([23]) # send location
96TTYPE = bytes([24]) # terminal type
97EOR = bytes([25]) # end or record
98TUID = bytes([26]) # TACACS user identification
99OUTMRK = bytes([27]) # output marking
100TTYLOC = bytes([28]) # terminal location number
101VT3270REGIME = bytes([29]) # 3270 regime
102X3PAD = bytes([30]) # X.3 PAD
103NAWS = bytes([31]) # window size
104TSPEED = bytes([32]) # terminal speed
105LFLOW = bytes([33]) # remote flow control
106LINEMODE = bytes([34]) # Linemode option
107XDISPLOC = bytes([35]) # X Display Location
108OLD_ENVIRON = bytes([36]) # Old - Environment variables
109AUTHENTICATION = bytes([37]) # Authenticate
110ENCRYPT = bytes([38]) # Encryption option
111NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000112# 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
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000116TN3270E = bytes([40]) # TN3270E
117XAUTH = bytes([41]) # XAUTH
118CHARSET = bytes([42]) # CHARSET
119RSP = bytes([43]) # Telnet Remote Serial Port
120COM_PORT_OPTION = bytes([44]) # Com Port Control Option
121SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
122TLS = bytes([46]) # Telnet Start TLS
123KERMIT = bytes([47]) # KERMIT
124SEND_URL = bytes([48]) # SEND-URL
125FORWARD_X = bytes([49]) # FORWARD_X
126PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
127SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
128PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
129EXOPL = bytes([255]) # Extended-Options-List
130NOOPT = bytes([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
Georg Brandlf78e02b2008-06-10 17:40:04 +0000187 def __init__(self, host=None, port=0,
188 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000189 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000190
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000191 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000192 With a hostname argument, it connects the instance; port number
193 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000194 """
195 self.debuglevel = DEBUGLEVEL
196 self.host = host
197 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000198 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000199 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000200 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000202 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000204 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000205 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000206 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000207 self.option_callback = None
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000208 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000209 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000210
Georg Brandlf78e02b2008-06-10 17:40:04 +0000211 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000212 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000213
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000214 The optional second argument is the port number, which
215 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000216
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000217 Don't try to reopen an already connected instance.
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
Georg Brandlf78e02b2008-06-10 17:40:04 +0000224 self.timeout = timeout
225 self.sock = socket.create_connection((host, port), timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000226
227 def __del__(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000228 """Destructor -- close the connection."""
229 self.close()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000230
231 def msg(self, msg, *args):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000232 """Print a debug message, when the debug level is > 0.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000233
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000234 If extra arguments are present, they are substituted in the
235 message using the standard string formatting operator.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000236
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000237 """
238 if self.debuglevel > 0:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000239 print('Telnet(%s,%d):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000240 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000241 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000242 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000243 print(msg)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000244
245 def set_debuglevel(self, debuglevel):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000246 """Set the debug level.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000247
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000248 The higher it is, the more debug output you get (on sys.stdout).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000249
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000250 """
251 self.debuglevel = debuglevel
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000252
253 def close(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 """Close the connection."""
255 if self.sock:
256 self.sock.close()
257 self.sock = 0
258 self.eof = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000259 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000260 self.sb = 0
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000261
262 def get_socket(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000263 """Return the socket object used internally."""
264 return self.sock
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000265
266 def fileno(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000267 """Return the fileno() of the socket object used internally."""
268 return self.sock.fileno()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000269
270 def write(self, buffer):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000271 """Write a string to the socket, doubling any IAC characters.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000272
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000273 Can block if the connection is blocked. May raise
274 socket.error if the connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000275
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000276 """
277 if IAC in buffer:
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000278 buffer = buffer.replace(IAC, IAC+IAC)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000279 self.msg("send %r", buffer)
Martin v. Löwise12454f2002-02-16 23:06:19 +0000280 self.sock.sendall(buffer)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000281
282 def read_until(self, match, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000283 """Read until a given string is encountered or until timeout.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000284
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000285 When no match is found, return whatever is available instead,
286 possibly the empty string. Raise EOFError if the connection
287 is closed and no cooked data is available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000288
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000289 """
290 n = len(match)
291 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000292 i = self.cookedq.find(match)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000293 if i >= 0:
294 i = i+n
295 buf = self.cookedq[:i]
296 self.cookedq = self.cookedq[i:]
297 return buf
298 s_reply = ([self], [], [])
299 s_args = s_reply
300 if timeout is not None:
301 s_args = s_args + (timeout,)
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000302 from time import time
303 time_start = time()
Guido van Rossum68468eb2003-02-27 20:14:51 +0000304 while not self.eof and select.select(*s_args) == s_reply:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000305 i = max(0, len(self.cookedq)-n)
306 self.fill_rawq()
307 self.process_rawq()
Eric S. Raymond6b8c5282001-02-09 07:10:12 +0000308 i = self.cookedq.find(match, i)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000309 if i >= 0:
310 i = i+n
311 buf = self.cookedq[:i]
312 self.cookedq = self.cookedq[i:]
313 return buf
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000314 if timeout is not None:
315 elapsed = time() - time_start
316 if elapsed >= timeout:
317 break
318 s_args = s_reply + (timeout-elapsed,)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000319 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000320
321 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000322 """Read all data until EOF; block until connection closed."""
323 self.process_rawq()
324 while not self.eof:
325 self.fill_rawq()
326 self.process_rawq()
327 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000328 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000329 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000330
331 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000333
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000334 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000335 available.
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.cookedq and not self.eof:
340 self.fill_rawq()
341 self.process_rawq()
342 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000343 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000344 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000345
346 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000348
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000349 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000350 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000351 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000352
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000353 """
354 self.process_rawq()
355 while not self.eof and self.sock_avail():
356 self.fill_rawq()
357 self.process_rawq()
358 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000359
360 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000362
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000363 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000364 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000365 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000366
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000367 """
368 self.process_rawq()
369 while not self.cookedq and not self.eof and self.sock_avail():
370 self.fill_rawq()
371 self.process_rawq()
372 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000373
374 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000375 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000376
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000377 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000378 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000379 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000380
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000381 """
382 self.process_rawq()
383 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000384
385 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000386 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000387
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000388 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000389 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000390
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """
392 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000393 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000394 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000395 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000397
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000398 def read_sb_data(self):
399 """Return any data available in the SB ... SE queue.
400
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000401 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000402 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000403 found, old unread SB data will be discarded. Don't block.
404
405 """
406 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000407 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000408 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000409
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000410 def set_option_negotiation_callback(self, callback):
411 """Provide a callback function called after each receipt of a telnet option."""
412 self.option_callback = callback
413
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000414 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000415 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000416
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000417 Set self.eof when connection is closed. Don't block unless in
418 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000419
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000420 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000421 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000422 try:
423 while self.rawq:
424 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000425 if not self.iacseq:
426 if c == theNULL:
427 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000428 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000429 continue
430 if c != IAC:
431 buf[self.sb] = buf[self.sb] + c
432 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000433 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000434 self.iacseq += c
435 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000436 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000437 if c in (DO, DONT, WILL, WONT):
438 self.iacseq += c
439 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000440
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000441 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000442 if c == IAC:
443 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000444 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000445 if c == SB: # SB ... SE start.
446 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000447 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000448 elif c == SE:
449 self.sb = 0
450 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000451 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000452 if self.option_callback:
453 # Callback is supposed to look into
454 # the sbdataq
455 self.option_callback(self.sock, c, NOOPT)
456 else:
457 # We can't offer automatic processing of
458 # suboptions. Alas, we should not get any
459 # unless we did a WILL/DO before.
460 self.msg('IAC %d not recognized' % ord(c))
461 elif len(self.iacseq) == 2:
462 cmd = self.iacseq[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000463 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000464 opt = c
465 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000466 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000467 cmd == DO and 'DO' or 'DONT', ord(opt))
468 if self.option_callback:
469 self.option_callback(self.sock, cmd, opt)
470 else:
471 self.sock.sendall(IAC + WONT + opt)
472 elif cmd in (WILL, WONT):
473 self.msg('IAC %s %d',
474 cmd == WILL and 'WILL' or 'WONT', ord(opt))
475 if self.option_callback:
476 self.option_callback(self.sock, cmd, opt)
477 else:
478 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000479 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000480 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000481 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000482 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000483 self.cookedq = self.cookedq + buf[0]
484 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000485
486 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000487 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000488
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000489 Block if no data is immediately available. Raise EOFError
490 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000491
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 """
493 if not self.rawq:
494 self.fill_rawq()
495 if self.eof:
496 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000497 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000498 self.irawq = self.irawq + 1
499 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000500 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000501 self.irawq = 0
502 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000503
504 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000505 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000506
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000507 Block if no data is immediately available. Set self.eof when
508 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000509
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000510 """
511 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000512 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000513 self.irawq = 0
514 # The buffer size should be fairly small so as to avoid quadratic
515 # behavior in process_rawq() above
516 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000517 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000518 self.eof = (not buf)
519 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000520
521 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000522 """Test whether data is available on the socket."""
523 return select.select([self], [], [], 0) == ([self], [], [])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000524
525 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000526 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000527 if sys.platform == "win32":
528 self.mt_interact()
529 return
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000530 while 1:
531 rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
532 if self in rfd:
533 try:
534 text = self.read_eager()
535 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000536 print('*** Connection closed by remote host ***')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000537 break
538 if text:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000539 sys.stdout.write(text.decode('ascii'))
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000540 sys.stdout.flush()
541 if sys.stdin in rfd:
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000542 line = sys.stdin.readline().encode('ascii')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000543 if not line:
544 break
545 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000546
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000547 def mt_interact(self):
548 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000549 import _thread
550 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000551 while 1:
552 line = sys.stdin.readline()
553 if not line:
554 break
555 self.write(line)
556
557 def listener(self):
558 """Helper for mt_interact() -- this executes in the other thread."""
559 while 1:
560 try:
561 data = self.read_eager()
562 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000563 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000564 return
565 if data:
566 sys.stdout.write(data)
567 else:
568 sys.stdout.flush()
569
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000570 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000571 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000572
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000573 The first argument is a list of regular expressions, either
574 compiled (re.RegexObject instances) or uncompiled (strings).
575 The optional second argument is a timeout, in seconds; default
576 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000577
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000578 Return a tuple of three items: the index in the list of the
579 first regular expression that matches; the match object
580 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000581
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000582 If EOF is read and no text was read, raise EOFError.
583 Otherwise, when nothing matches, return (-1, None, text) where
584 text is the text received so far (may be the empty string if a
585 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000586
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 If a regular expression ends with a greedy match (e.g. '.*')
588 or if more than one expression can match the same input, the
589 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000590
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000591 """
592 re = None
593 list = list[:]
594 indices = range(len(list))
595 for i in indices:
596 if not hasattr(list[i], "search"):
597 if not re: import re
598 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000599 if timeout is not None:
600 from time import time
601 time_start = time()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000602 while 1:
603 self.process_rawq()
604 for i in indices:
605 m = list[i].search(self.cookedq)
606 if m:
607 e = m.end()
608 text = self.cookedq[:e]
609 self.cookedq = self.cookedq[e:]
610 return (i, m, text)
611 if self.eof:
612 break
613 if timeout is not None:
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000614 elapsed = time() - time_start
615 if elapsed >= timeout:
616 break
617 s_args = ([self.fileno()], [], [], timeout-elapsed)
618 r, w, x = select.select(*s_args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000619 if not r:
620 break
621 self.fill_rawq()
622 text = self.read_very_lazy()
623 if not text and self.eof:
624 raise EOFError
625 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000626
627
628def test():
629 """Test program for telnetlib.
630
631 Usage: python telnetlib.py [-d] ... [host [port]]
632
633 Default host is localhost; default port is 23.
634
635 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000636 debuglevel = 0
637 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000638 debuglevel = debuglevel+1
639 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000640 host = 'localhost'
641 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000642 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000643 port = 0
644 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000645 portstr = sys.argv[2]
646 try:
647 port = int(portstr)
648 except ValueError:
649 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000650 tn = Telnet()
651 tn.set_debuglevel(debuglevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000652 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000653 tn.interact()
654 tn.close()
655
656if __name__ == '__main__':
657 test()