blob: 0cacac85fa0e074fdd16dc42e10c9366aa941769 [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
Charles-François Natali64590252013-10-21 14:02:12 +020020It is possible to pass a Telnet object to a selector in order to wait until
21more data is available. Note that in this case, read_eager() may return b''
22even if there was data on the socket, because the protocol negotiation may have
23eaten the data. This is why EOFError is needed in some cases to distinguish
24between "no data" and "connection closed" (since the socket also appears ready
25for reading when it is closed).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000026
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000027To do:
28- option negotiation
Guido van Rossumccb5ec61997-12-24 22:24:19 +000029- timeout should be intrinsic to the connection object instead of an
30 option on one of the read calls only
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000031
32"""
33
34
35# Imported modules
Guido van Rossumccb5ec61997-12-24 22:24:19 +000036import sys
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000037import socket
Charles-François Natali64590252013-10-21 14:02:12 +020038import selectors
Victor Stinner2ff68dd2013-10-26 09:16:29 +020039try:
40 from time import monotonic as _time
41except ImportError:
42 from time import time as _time
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)
Jack Diederich1c8f38c2009-04-10 05:33:26 +000053IAC = bytes([255]) # "Interpret As Command"
54DONT = bytes([254])
55DO = bytes([253])
56WONT = bytes([252])
57WILL = bytes([251])
58theNULL = bytes([0])
Martin v. Löwis574deae2002-11-04 17:34:07 +000059
Jack Diederich1c8f38c2009-04-10 05:33:26 +000060SE = bytes([240]) # Subnegotiation End
61NOP = bytes([241]) # No Operation
62DM = bytes([242]) # Data Mark
63BRK = bytes([243]) # Break
64IP = bytes([244]) # Interrupt process
65AO = bytes([245]) # Abort output
66AYT = bytes([246]) # Are You There
67EC = bytes([247]) # Erase Character
68EL = bytes([248]) # Erase Line
69GA = bytes([249]) # Go Ahead
70SB = bytes([250]) # Subnegotiation Begin
Martin v. Löwis574deae2002-11-04 17:34:07 +000071
Guido van Rossumb9b50eb1997-12-24 21:07:04 +000072
Martin v. Löwisb0162f92001-09-06 08:51:38 +000073# Telnet protocol options code (don't change)
74# These ones all come from arpa/telnet.h
Jack Diederich1c8f38c2009-04-10 05:33:26 +000075BINARY = bytes([0]) # 8-bit data path
76ECHO = bytes([1]) # echo
77RCP = bytes([2]) # prepare to reconnect
78SGA = bytes([3]) # suppress go ahead
79NAMS = bytes([4]) # approximate message size
80STATUS = bytes([5]) # give status
81TM = bytes([6]) # timing mark
82RCTE = bytes([7]) # remote controlled transmission and echo
83NAOL = bytes([8]) # negotiate about output line width
84NAOP = bytes([9]) # negotiate about output page size
85NAOCRD = bytes([10]) # negotiate about CR disposition
86NAOHTS = bytes([11]) # negotiate about horizontal tabstops
87NAOHTD = bytes([12]) # negotiate about horizontal tab disposition
88NAOFFD = bytes([13]) # negotiate about formfeed disposition
89NAOVTS = bytes([14]) # negotiate about vertical tab stops
90NAOVTD = bytes([15]) # negotiate about vertical tab disposition
91NAOLFD = bytes([16]) # negotiate about output LF disposition
92XASCII = bytes([17]) # extended ascii character set
93LOGOUT = bytes([18]) # force logout
94BM = bytes([19]) # byte macro
95DET = bytes([20]) # data entry terminal
96SUPDUP = bytes([21]) # supdup protocol
97SUPDUPOUTPUT = bytes([22]) # supdup output
98SNDLOC = bytes([23]) # send location
99TTYPE = bytes([24]) # terminal type
100EOR = bytes([25]) # end or record
101TUID = bytes([26]) # TACACS user identification
102OUTMRK = bytes([27]) # output marking
103TTYLOC = bytes([28]) # terminal location number
104VT3270REGIME = bytes([29]) # 3270 regime
105X3PAD = bytes([30]) # X.3 PAD
106NAWS = bytes([31]) # window size
107TSPEED = bytes([32]) # terminal speed
108LFLOW = bytes([33]) # remote flow control
109LINEMODE = bytes([34]) # Linemode option
110XDISPLOC = bytes([35]) # X Display Location
111OLD_ENVIRON = bytes([36]) # Old - Environment variables
112AUTHENTICATION = bytes([37]) # Authenticate
113ENCRYPT = bytes([38]) # Encryption option
114NEW_ENVIRON = bytes([39]) # New - Environment variables
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000115# the following ones come from
116# http://www.iana.org/assignments/telnet-options
117# Unfortunately, that document does not assign identifiers
118# to all of them, so we are making them up
Jack Diederich1c8f38c2009-04-10 05:33:26 +0000119TN3270E = bytes([40]) # TN3270E
120XAUTH = bytes([41]) # XAUTH
121CHARSET = bytes([42]) # CHARSET
122RSP = bytes([43]) # Telnet Remote Serial Port
123COM_PORT_OPTION = bytes([44]) # Com Port Control Option
124SUPPRESS_LOCAL_ECHO = bytes([45]) # Telnet Suppress Local Echo
125TLS = bytes([46]) # Telnet Start TLS
126KERMIT = bytes([47]) # KERMIT
127SEND_URL = bytes([48]) # SEND-URL
128FORWARD_X = bytes([49]) # FORWARD_X
129PRAGMA_LOGON = bytes([138]) # TELOPT PRAGMA LOGON
130SSPI_LOGON = bytes([139]) # TELOPT SSPI LOGON
131PRAGMA_HEARTBEAT = bytes([140]) # TELOPT PRAGMA HEARTBEAT
132EXOPL = bytes([255]) # Extended-Options-List
133NOOPT = bytes([0])
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000134
Charles-François Natali64590252013-10-21 14:02:12 +0200135
136# poll/select have the advantage of not requiring any extra file descriptor,
137# contrarily to epoll/kqueue (also, they require a single syscall).
138if hasattr(selectors, 'PollSelector'):
139 _TelnetSelector = selectors.PollSelector
140else:
141 _TelnetSelector = selectors.SelectSelector
142
143
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000144class Telnet:
145
146 """Telnet interface class.
147
148 An instance of this class represents a connection to a telnet
149 server. The instance is initially not connected; the open()
150 method must be used to establish a connection. Alternatively, the
151 host name and optional port number can be passed to the
152 constructor, too.
153
154 Don't try to reopen an already connected instance.
155
156 This class has many read_*() methods. Note that some of them
157 raise EOFError when the end of the connection is read, because
158 they can return an empty string for other reasons. See the
159 individual doc strings.
160
161 read_until(expected, [timeout])
162 Read until the expected string has been seen, or a timeout is
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000163 hit (default is no timeout); may block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000164
165 read_all()
166 Read all data until EOF; may block.
167
168 read_some()
169 Read at least one byte or EOF; may block.
170
171 read_very_eager()
172 Read all data available already queued or on the socket,
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000173 without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000174
175 read_eager()
176 Read either data already queued or some data available on the
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000177 socket, without blocking.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000178
179 read_lazy()
180 Read all data in the raw queue (processing it first), without
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000181 doing any socket I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000182
183 read_very_lazy()
184 Reads all data in the cooked queue, without doing any socket
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000185 I/O.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000186
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000187 read_sb_data()
188 Reads available data between SB ... SE sequence. Don't block.
189
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000190 set_option_negotiation_callback(callback)
191 Each time a telnet option is read on the input flow, this callback
192 (if set) is called with the following parameters :
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000193 callback(telnet socket, command, option)
194 option will be chr(0) when there is no option.
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000195 No other action is done afterwards by telnetlib.
196
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000197 """
198
Georg Brandlf78e02b2008-06-10 17:40:04 +0000199 def __init__(self, host=None, port=0,
200 timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000201 """Constructor.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000202
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000203 When called without arguments, create an unconnected instance.
Georg Brandlf78e02b2008-06-10 17:40:04 +0000204 With a hostname argument, it connects the instance; port number
205 and timeout are optional.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000206 """
207 self.debuglevel = DEBUGLEVEL
208 self.host = host
209 self.port = port
Guido van Rossumd8faa362007-04-27 19:54:29 +0000210 self.timeout = timeout
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000211 self.sock = None
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000212 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000213 self.irawq = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000214 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000215 self.eof = 0
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000216 self.iacseq = b'' # Buffer for IAC sequence.
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000217 self.sb = 0 # flag for SB and SE sequence.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000218 self.sbdataq = b''
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000219 self.option_callback = None
Raymond Hettinger10ff7062002-06-02 03:04:52 +0000220 if host is not None:
Guido van Rossumd8faa362007-04-27 19:54:29 +0000221 self.open(host, port, timeout)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000222
Georg Brandlf78e02b2008-06-10 17:40:04 +0000223 def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000224 """Connect to a host.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000225
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000226 The optional second argument is the port number, which
227 defaults to the standard telnet port (23).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000228
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000229 Don't try to reopen an already connected instance.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000230 """
231 self.eof = 0
232 if not port:
233 port = TELNET_PORT
234 self.host = host
235 self.port = port
Georg Brandlf78e02b2008-06-10 17:40:04 +0000236 self.timeout = timeout
237 self.sock = socket.create_connection((host, port), timeout)
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:
R. David Murray32ef70c2010-12-14 14:16:20 +0000251 print('Telnet(%s,%s):' % (self.host, self.port), end=' ')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000252 if args:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000253 print(msg % args)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000254 else:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000255 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
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000271 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000272 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
Andrew Svetlov0832af62012-12-18 23:10:48 +0200286 OSError 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
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000310 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200311 deadline = _time() + timeout
Charles-François Natali64590252013-10-21 14:02:12 +0200312 with _TelnetSelector() as selector:
313 selector.register(self, selectors.EVENT_READ)
314 while not self.eof:
315 if selector.select(timeout):
316 i = max(0, len(self.cookedq)-n)
317 self.fill_rawq()
318 self.process_rawq()
319 i = self.cookedq.find(match, i)
320 if i >= 0:
321 i = i+n
322 buf = self.cookedq[:i]
323 self.cookedq = self.cookedq[i:]
324 return buf
325 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200326 timeout = deadline - _time()
Charles-François Natali64590252013-10-21 14:02:12 +0200327 if timeout < 0:
328 break
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000329 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000330
331 def read_all(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000332 """Read all data until EOF; block until connection closed."""
333 self.process_rawq()
334 while not self.eof:
335 self.fill_rawq()
336 self.process_rawq()
337 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000338 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000339 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000340
341 def read_some(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000342 """Read at least one byte of cooked data unless EOF is hit.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000343
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000344 Return b'' if EOF is hit. Block if no data is immediately
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000345 available.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000346
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000347 """
348 self.process_rawq()
349 while not self.cookedq and not self.eof:
350 self.fill_rawq()
351 self.process_rawq()
352 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000353 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000354 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000355
356 def read_very_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000357 """Read everything that's possible without blocking in I/O (eager).
Tim Petersb90f89a2001-01-15 03:26:36 +0000358
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000359 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000360 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000361 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000362
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000363 """
364 self.process_rawq()
365 while not self.eof and self.sock_avail():
366 self.fill_rawq()
367 self.process_rawq()
368 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000369
370 def read_eager(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000371 """Read readily available data.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000372
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000373 Raise EOFError if connection closed and no cooked data
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000374 available. Return b'' if no cooked data available otherwise.
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000375 Don't block unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000376
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000377 """
378 self.process_rawq()
379 while not self.cookedq and not self.eof and self.sock_avail():
380 self.fill_rawq()
381 self.process_rawq()
382 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000383
384 def read_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000385 """Process and return data that's already in the queues (lazy).
Tim Petersb90f89a2001-01-15 03:26:36 +0000386
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000387 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000388 Return b'' if no cooked data available otherwise. Don't block
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000389 unless in the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000390
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000391 """
392 self.process_rawq()
393 return self.read_very_lazy()
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000394
395 def read_very_lazy(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000396 """Return any data available in the cooked queue (very lazy).
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000397
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000398 Raise EOFError if connection closed and no data available.
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000399 Return b'' if no cooked data available otherwise. Don't block.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000400
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000401 """
402 buf = self.cookedq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000403 self.cookedq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000404 if not buf and self.eof and not self.rawq:
Collin Winterce36ad82007-08-30 01:19:48 +0000405 raise EOFError('telnet connection closed')
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000406 return buf
Tim Peters230a60c2002-11-09 05:08:07 +0000407
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000408 def read_sb_data(self):
409 """Return any data available in the SB ... SE queue.
410
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000411 Return b'' if no SB ... SE available. Should only be called
Tim Peters230a60c2002-11-09 05:08:07 +0000412 after seeing a SB or SE command. When a new SB command is
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000413 found, old unread SB data will be discarded. Don't block.
414
415 """
416 buf = self.sbdataq
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000417 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000418 return buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000419
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000420 def set_option_negotiation_callback(self, callback):
421 """Provide a callback function called after each receipt of a telnet option."""
422 self.option_callback = callback
423
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000424 def process_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000425 """Transfer from raw queue to cooked queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000426
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000427 Set self.eof when connection is closed. Don't block unless in
428 the midst of an IAC sequence.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000429
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000430 """
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000431 buf = [b'', b'']
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000432 try:
433 while self.rawq:
434 c = self.rawq_getchar()
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000435 if not self.iacseq:
436 if c == theNULL:
437 continue
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000438 if c == b"\021":
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000439 continue
440 if c != IAC:
441 buf[self.sb] = buf[self.sb] + c
442 continue
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000443 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000444 self.iacseq += c
445 elif len(self.iacseq) == 1:
Thomas Wouters49fd7fa2006-04-21 10:40:58 +0000446 # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000447 if c in (DO, DONT, WILL, WONT):
448 self.iacseq += c
449 continue
Tim Peters230a60c2002-11-09 05:08:07 +0000450
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000451 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000452 if c == IAC:
453 buf[self.sb] = buf[self.sb] + c
Martin v. Löwisb0162f92001-09-06 08:51:38 +0000454 else:
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000455 if c == SB: # SB ... SE start.
456 self.sb = 1
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000457 self.sbdataq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000458 elif c == SE:
459 self.sb = 0
460 self.sbdataq = self.sbdataq + buf[1]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000461 buf[1] = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000462 if self.option_callback:
463 # Callback is supposed to look into
464 # the sbdataq
465 self.option_callback(self.sock, c, NOOPT)
466 else:
467 # We can't offer automatic processing of
468 # suboptions. Alas, we should not get any
469 # unless we did a WILL/DO before.
470 self.msg('IAC %d not recognized' % ord(c))
471 elif len(self.iacseq) == 2:
Jack Diederich36596a32009-07-26 22:23:04 +0000472 cmd = self.iacseq[1:2]
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000473 self.iacseq = b''
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000474 opt = c
475 if cmd in (DO, DONT):
Tim Peters230a60c2002-11-09 05:08:07 +0000476 self.msg('IAC %s %d',
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000477 cmd == DO and 'DO' or 'DONT', ord(opt))
478 if self.option_callback:
479 self.option_callback(self.sock, cmd, opt)
480 else:
481 self.sock.sendall(IAC + WONT + opt)
482 elif cmd in (WILL, WONT):
483 self.msg('IAC %s %d',
484 cmd == WILL and 'WILL' or 'WONT', ord(opt))
485 if self.option_callback:
486 self.option_callback(self.sock, cmd, opt)
487 else:
488 self.sock.sendall(IAC + DONT + opt)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000489 except EOFError: # raised by self.rawq_getchar()
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000490 self.iacseq = b'' # Reset on EOF
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000491 self.sb = 0
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000492 pass
Martin v. Löwis1da9c572002-11-04 09:56:00 +0000493 self.cookedq = self.cookedq + buf[0]
494 self.sbdataq = self.sbdataq + buf[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000495
496 def rawq_getchar(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000497 """Get next char from raw queue.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000498
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000499 Block if no data is immediately available. Raise EOFError
500 when connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000501
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000502 """
503 if not self.rawq:
504 self.fill_rawq()
505 if self.eof:
506 raise EOFError
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000507 c = self.rawq[self.irawq:self.irawq+1]
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000508 self.irawq = self.irawq + 1
509 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000510 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000511 self.irawq = 0
512 return c
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000513
514 def fill_rawq(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000515 """Fill raw queue from exactly one recv() system call.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000516
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000517 Block if no data is immediately available. Set self.eof when
518 connection is closed.
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000519
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000520 """
521 if self.irawq >= len(self.rawq):
Benjamin Peterson3de7fb82008-10-15 20:54:24 +0000522 self.rawq = b''
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000523 self.irawq = 0
524 # The buffer size should be fairly small so as to avoid quadratic
525 # behavior in process_rawq() above
526 buf = self.sock.recv(50)
Walter Dörwald70a6b492004-02-12 17:35:32 +0000527 self.msg("recv %r", buf)
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000528 self.eof = (not buf)
529 self.rawq = self.rawq + buf
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000530
531 def sock_avail(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000532 """Test whether data is available on the socket."""
Charles-François Natali64590252013-10-21 14:02:12 +0200533 with _TelnetSelector() as selector:
534 selector.register(self, selectors.EVENT_READ)
535 return bool(selector.select(0))
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000536
537 def interact(self):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000538 """Interaction function, emulates a very dumb telnet client."""
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000539 if sys.platform == "win32":
540 self.mt_interact()
541 return
Charles-François Natali64590252013-10-21 14:02:12 +0200542 with _TelnetSelector() as selector:
543 selector.register(self, selectors.EVENT_READ)
544 selector.register(sys.stdin, selectors.EVENT_READ)
545
546 while True:
547 for key, events in selector.select():
548 if key.fileobj is self:
549 try:
550 text = self.read_eager()
551 except EOFError:
552 print('*** Connection closed by remote host ***')
553 return
554 if text:
555 sys.stdout.write(text.decode('ascii'))
556 sys.stdout.flush()
557 elif key.fileobj is sys.stdin:
558 line = sys.stdin.readline().encode('ascii')
559 if not line:
560 return
561 self.write(line)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000562
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000563 def mt_interact(self):
564 """Multithreaded version of interact()."""
Georg Brandl2067bfd2008-05-25 13:05:15 +0000565 import _thread
566 _thread.start_new_thread(self.listener, ())
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000567 while 1:
568 line = sys.stdin.readline()
569 if not line:
570 break
R. David Murrayba488d12010-10-26 12:42:24 +0000571 self.write(line.encode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000572
573 def listener(self):
574 """Helper for mt_interact() -- this executes in the other thread."""
575 while 1:
576 try:
577 data = self.read_eager()
578 except EOFError:
Guido van Rossumbe19ed72007-02-09 05:37:30 +0000579 print('*** Connection closed by remote host ***')
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000580 return
581 if data:
R. David Murrayba488d12010-10-26 12:42:24 +0000582 sys.stdout.write(data.decode('ascii'))
Guido van Rossum82eae9e1998-12-23 23:04:17 +0000583 else:
584 sys.stdout.flush()
585
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000586 def expect(self, list, timeout=None):
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000587 """Read until one from a list of a regular expressions matches.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000588
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000589 The first argument is a list of regular expressions, either
590 compiled (re.RegexObject instances) or uncompiled (strings).
591 The optional second argument is a timeout, in seconds; default
592 is no timeout.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000593
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000594 Return a tuple of three items: the index in the list of the
595 first regular expression that matches; the match object
596 returned; and the text read up till and including the match.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000597
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000598 If EOF is read and no text was read, raise EOFError.
599 Otherwise, when nothing matches, return (-1, None, text) where
600 text is the text received so far (may be the empty string if a
601 timeout happened).
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000602
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000603 If a regular expression ends with a greedy match (e.g. '.*')
604 or if more than one expression can match the same input, the
605 results are undeterministic, and may depend on the I/O timing.
Guido van Rossumccb5ec61997-12-24 22:24:19 +0000606
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000607 """
608 re = None
609 list = list[:]
610 indices = range(len(list))
611 for i in indices:
612 if not hasattr(list[i], "search"):
613 if not re: import re
614 list[i] = re.compile(list[i])
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000615 if timeout is not None:
Victor Stinnerebca3922013-10-26 09:20:38 +0200616 deadline = _time() + timeout
Charles-François Natali64590252013-10-21 14:02:12 +0200617 with _TelnetSelector() as selector:
618 selector.register(self, selectors.EVENT_READ)
619 while not self.eof:
620 self.process_rawq()
621 for i in indices:
622 m = list[i].search(self.cookedq)
623 if m:
624 e = m.end()
625 text = self.cookedq[:e]
626 self.cookedq = self.cookedq[e:]
627 return (i, m, text)
628 if timeout is not None:
629 ready = selector.select(timeout)
Victor Stinnerebca3922013-10-26 09:20:38 +0200630 timeout = deadline - _time()
Charles-François Natali64590252013-10-21 14:02:12 +0200631 if not ready:
632 if timeout < 0:
633 break
634 else:
635 continue
636 self.fill_rawq()
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000637 text = self.read_very_lazy()
638 if not text and self.eof:
639 raise EOFError
640 return (-1, None, text)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000641
642
643def test():
644 """Test program for telnetlib.
645
646 Usage: python telnetlib.py [-d] ... [host [port]]
647
648 Default host is localhost; default port is 23.
649
650 """
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000651 debuglevel = 0
652 while sys.argv[1:] and sys.argv[1] == '-d':
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000653 debuglevel = debuglevel+1
654 del sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000655 host = 'localhost'
656 if sys.argv[1:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000657 host = sys.argv[1]
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000658 port = 0
659 if sys.argv[2:]:
Guido van Rossum45e2fbc1998-03-26 21:13:24 +0000660 portstr = sys.argv[2]
661 try:
662 port = int(portstr)
663 except ValueError:
664 port = socket.getservbyname(portstr, 'tcp')
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000665 tn = Telnet()
666 tn.set_debuglevel(debuglevel)
Guido van Rossumd8faa362007-04-27 19:54:29 +0000667 tn.open(host, port, timeout=0.5)
Guido van Rossumb9b50eb1997-12-24 21:07:04 +0000668 tn.interact()
669 tn.close()
670
671if __name__ == '__main__':
672 test()