|
@@ -0,0 +1,793 @@
|
|
1
|
+# This whole file is a copy of the 'telnetlib.py' that came with Python 2.7.9 distribution.
|
|
2
|
+# A patch was applied to this file, in order to stop dropping null (0x00) characters.
|
|
3
|
+
|
|
4
|
+r"""TELNET client class.
|
|
5
|
+
|
|
6
|
+Based on RFC 854: TELNET Protocol Specification, by J. Postel and
|
|
7
|
+J. Reynolds
|
|
8
|
+
|
|
9
|
+Example:
|
|
10
|
+
|
|
11
|
+>>> from telnetlib import Telnet
|
|
12
|
+>>> tn = Telnet('www.python.org', 79) # connect to finger port
|
|
13
|
+>>> tn.write('guido\r\n')
|
|
14
|
+>>> print tn.read_all()
|
|
15
|
+Login Name TTY Idle When Where
|
|
16
|
+guido Guido van Rossum pts/2 <Dec 2 11:10> snag.cnri.reston..
|
|
17
|
+
|
|
18
|
+>>>
|
|
19
|
+
|
|
20
|
+Note that read_all() won't read until eof -- it just reads some data
|
|
21
|
+-- but it guarantees to read at least one byte unless EOF is hit.
|
|
22
|
+
|
|
23
|
+It is possible to pass a Telnet object to select.select() in order to
|
|
24
|
+wait until more data is available. Note that in this case,
|
|
25
|
+read_eager() may return '' even if there was data on the socket,
|
|
26
|
+because the protocol negotiation may have eaten the data. This is why
|
|
27
|
+EOFError is needed in some cases to distinguish between "no data" and
|
|
28
|
+"connection closed" (since the socket also appears ready for reading
|
|
29
|
+when it is closed).
|
|
30
|
+
|
|
31
|
+To do:
|
|
32
|
+- option negotiation
|
|
33
|
+- timeout should be intrinsic to the connection object instead of an
|
|
34
|
+ option on one of the read calls only
|
|
35
|
+
|
|
36
|
+"""
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+# Imported modules
|
|
40
|
+import errno
|
|
41
|
+import sys
|
|
42
|
+import socket
|
|
43
|
+import select
|
|
44
|
+
|
|
45
|
+__all__ = ["Telnet"]
|
|
46
|
+
|
|
47
|
+# Tunable parameters
|
|
48
|
+DEBUGLEVEL = 0
|
|
49
|
+
|
|
50
|
+# Telnet protocol defaults
|
|
51
|
+TELNET_PORT = 23
|
|
52
|
+
|
|
53
|
+# Telnet protocol characters (don't change)
|
|
54
|
+IAC = chr(255) # "Interpret As Command"
|
|
55
|
+DONT = chr(254)
|
|
56
|
+DO = chr(253)
|
|
57
|
+WONT = chr(252)
|
|
58
|
+WILL = chr(251)
|
|
59
|
+theNULL = chr(0)
|
|
60
|
+
|
|
61
|
+SE = chr(240) # Subnegotiation End
|
|
62
|
+NOP = chr(241) # No Operation
|
|
63
|
+DM = chr(242) # Data Mark
|
|
64
|
+BRK = chr(243) # Break
|
|
65
|
+IP = chr(244) # Interrupt process
|
|
66
|
+AO = chr(245) # Abort output
|
|
67
|
+AYT = chr(246) # Are You There
|
|
68
|
+EC = chr(247) # Erase Character
|
|
69
|
+EL = chr(248) # Erase Line
|
|
70
|
+GA = chr(249) # Go Ahead
|
|
71
|
+SB = chr(250) # Subnegotiation Begin
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+# Telnet protocol options code (don't change)
|
|
75
|
+# These ones all come from arpa/telnet.h
|
|
76
|
+BINARY = chr(0) # 8-bit data path
|
|
77
|
+ECHO = chr(1) # echo
|
|
78
|
+RCP = chr(2) # prepare to reconnect
|
|
79
|
+SGA = chr(3) # suppress go ahead
|
|
80
|
+NAMS = chr(4) # approximate message size
|
|
81
|
+STATUS = chr(5) # give status
|
|
82
|
+TM = chr(6) # timing mark
|
|
83
|
+RCTE = chr(7) # remote controlled transmission and echo
|
|
84
|
+NAOL = chr(8) # negotiate about output line width
|
|
85
|
+NAOP = chr(9) # negotiate about output page size
|
|
86
|
+NAOCRD = chr(10) # negotiate about CR disposition
|
|
87
|
+NAOHTS = chr(11) # negotiate about horizontal tabstops
|
|
88
|
+NAOHTD = chr(12) # negotiate about horizontal tab disposition
|
|
89
|
+NAOFFD = chr(13) # negotiate about formfeed disposition
|
|
90
|
+NAOVTS = chr(14) # negotiate about vertical tab stops
|
|
91
|
+NAOVTD = chr(15) # negotiate about vertical tab disposition
|
|
92
|
+NAOLFD = chr(16) # negotiate about output LF disposition
|
|
93
|
+XASCII = chr(17) # extended ascii character set
|
|
94
|
+LOGOUT = chr(18) # force logout
|
|
95
|
+BM = chr(19) # byte macro
|
|
96
|
+DET = chr(20) # data entry terminal
|
|
97
|
+SUPDUP = chr(21) # supdup protocol
|
|
98
|
+SUPDUPOUTPUT = chr(22) # supdup output
|
|
99
|
+SNDLOC = chr(23) # send location
|
|
100
|
+TTYPE = chr(24) # terminal type
|
|
101
|
+EOR = chr(25) # end or record
|
|
102
|
+TUID = chr(26) # TACACS user identification
|
|
103
|
+OUTMRK = chr(27) # output marking
|
|
104
|
+TTYLOC = chr(28) # terminal location number
|
|
105
|
+VT3270REGIME = chr(29) # 3270 regime
|
|
106
|
+X3PAD = chr(30) # X.3 PAD
|
|
107
|
+NAWS = chr(31) # window size
|
|
108
|
+TSPEED = chr(32) # terminal speed
|
|
109
|
+LFLOW = chr(33) # remote flow control
|
|
110
|
+LINEMODE = chr(34) # Linemode option
|
|
111
|
+XDISPLOC = chr(35) # X Display Location
|
|
112
|
+OLD_ENVIRON = chr(36) # Old - Environment variables
|
|
113
|
+AUTHENTICATION = chr(37) # Authenticate
|
|
114
|
+ENCRYPT = chr(38) # Encryption option
|
|
115
|
+NEW_ENVIRON = chr(39) # New - Environment variables
|
|
116
|
+# the following ones come from
|
|
117
|
+# http://www.iana.org/assignments/telnet-options
|
|
118
|
+# Unfortunately, that document does not assign identifiers
|
|
119
|
+# to all of them, so we are making them up
|
|
120
|
+TN3270E = chr(40) # TN3270E
|
|
121
|
+XAUTH = chr(41) # XAUTH
|
|
122
|
+CHARSET = chr(42) # CHARSET
|
|
123
|
+RSP = chr(43) # Telnet Remote Serial Port
|
|
124
|
+COM_PORT_OPTION = chr(44) # Com Port Control Option
|
|
125
|
+SUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local Echo
|
|
126
|
+TLS = chr(46) # Telnet Start TLS
|
|
127
|
+KERMIT = chr(47) # KERMIT
|
|
128
|
+SEND_URL = chr(48) # SEND-URL
|
|
129
|
+FORWARD_X = chr(49) # FORWARD_X
|
|
130
|
+PRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGON
|
|
131
|
+SSPI_LOGON = chr(139) # TELOPT SSPI LOGON
|
|
132
|
+PRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEAT
|
|
133
|
+EXOPL = chr(255) # Extended-Options-List
|
|
134
|
+NOOPT = chr(0)
|
|
135
|
+
|
|
136
|
+class Telnet:
|
|
137
|
+
|
|
138
|
+ """Telnet interface class.
|
|
139
|
+
|
|
140
|
+ An instance of this class represents a connection to a telnet
|
|
141
|
+ server. The instance is initially not connected; the open()
|
|
142
|
+ method must be used to establish a connection. Alternatively, the
|
|
143
|
+ host name and optional port number can be passed to the
|
|
144
|
+ constructor, too.
|
|
145
|
+
|
|
146
|
+ Don't try to reopen an already connected instance.
|
|
147
|
+
|
|
148
|
+ This class has many read_*() methods. Note that some of them
|
|
149
|
+ raise EOFError when the end of the connection is read, because
|
|
150
|
+ they can return an empty string for other reasons. See the
|
|
151
|
+ individual doc strings.
|
|
152
|
+
|
|
153
|
+ read_until(expected, [timeout])
|
|
154
|
+ Read until the expected string has been seen, or a timeout is
|
|
155
|
+ hit (default is no timeout); may block.
|
|
156
|
+
|
|
157
|
+ read_all()
|
|
158
|
+ Read all data until EOF; may block.
|
|
159
|
+
|
|
160
|
+ read_some()
|
|
161
|
+ Read at least one byte or EOF; may block.
|
|
162
|
+
|
|
163
|
+ read_very_eager()
|
|
164
|
+ Read all data available already queued or on the socket,
|
|
165
|
+ without blocking.
|
|
166
|
+
|
|
167
|
+ read_eager()
|
|
168
|
+ Read either data already queued or some data available on the
|
|
169
|
+ socket, without blocking.
|
|
170
|
+
|
|
171
|
+ read_lazy()
|
|
172
|
+ Read all data in the raw queue (processing it first), without
|
|
173
|
+ doing any socket I/O.
|
|
174
|
+
|
|
175
|
+ read_very_lazy()
|
|
176
|
+ Reads all data in the cooked queue, without doing any socket
|
|
177
|
+ I/O.
|
|
178
|
+
|
|
179
|
+ read_sb_data()
|
|
180
|
+ Reads available data between SB ... SE sequence. Don't block.
|
|
181
|
+
|
|
182
|
+ set_option_negotiation_callback(callback)
|
|
183
|
+ Each time a telnet option is read on the input flow, this callback
|
|
184
|
+ (if set) is called with the following parameters :
|
|
185
|
+ callback(telnet socket, command, option)
|
|
186
|
+ option will be chr(0) when there is no option.
|
|
187
|
+ No other action is done afterwards by telnetlib.
|
|
188
|
+
|
|
189
|
+ """
|
|
190
|
+
|
|
191
|
+ def __init__(self, host=None, port=0,
|
|
192
|
+ timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
|
|
193
|
+ """Constructor.
|
|
194
|
+
|
|
195
|
+ When called without arguments, create an unconnected instance.
|
|
196
|
+ With a hostname argument, it connects the instance; port number
|
|
197
|
+ and timeout are optional.
|
|
198
|
+ """
|
|
199
|
+ self.debuglevel = DEBUGLEVEL
|
|
200
|
+ self.host = host
|
|
201
|
+ self.port = port
|
|
202
|
+ self.timeout = timeout
|
|
203
|
+ self.sock = None
|
|
204
|
+ self.rawq = ''
|
|
205
|
+ self.irawq = 0
|
|
206
|
+ self.cookedq = ''
|
|
207
|
+ self.eof = 0
|
|
208
|
+ self.iacseq = '' # Buffer for IAC sequence.
|
|
209
|
+ self.sb = 0 # flag for SB and SE sequence.
|
|
210
|
+ self.sbdataq = ''
|
|
211
|
+ self.option_callback = None
|
|
212
|
+ self._has_poll = hasattr(select, 'poll')
|
|
213
|
+ if host is not None:
|
|
214
|
+ self.open(host, port, timeout)
|
|
215
|
+
|
|
216
|
+ def open(self, host, port=0, timeout=socket._GLOBAL_DEFAULT_TIMEOUT):
|
|
217
|
+ """Connect to a host.
|
|
218
|
+
|
|
219
|
+ The optional second argument is the port number, which
|
|
220
|
+ defaults to the standard telnet port (23).
|
|
221
|
+
|
|
222
|
+ Don't try to reopen an already connected instance.
|
|
223
|
+ """
|
|
224
|
+ self.eof = 0
|
|
225
|
+ if not port:
|
|
226
|
+ port = TELNET_PORT
|
|
227
|
+ self.host = host
|
|
228
|
+ self.port = port
|
|
229
|
+ self.timeout = timeout
|
|
230
|
+ self.sock = socket.create_connection((host, port), timeout)
|
|
231
|
+
|
|
232
|
+ def __del__(self):
|
|
233
|
+ """Destructor -- close the connection."""
|
|
234
|
+ self.close()
|
|
235
|
+
|
|
236
|
+ def msg(self, msg, *args):
|
|
237
|
+ """Print a debug message, when the debug level is > 0.
|
|
238
|
+
|
|
239
|
+ If extra arguments are present, they are substituted in the
|
|
240
|
+ message using the standard string formatting operator.
|
|
241
|
+
|
|
242
|
+ """
|
|
243
|
+ if self.debuglevel > 0:
|
|
244
|
+ print 'Telnet(%s,%s):' % (self.host, self.port),
|
|
245
|
+ if args:
|
|
246
|
+ print msg % args
|
|
247
|
+ else:
|
|
248
|
+ print msg
|
|
249
|
+
|
|
250
|
+ def set_debuglevel(self, debuglevel):
|
|
251
|
+ """Set the debug level.
|
|
252
|
+
|
|
253
|
+ The higher it is, the more debug output you get (on sys.stdout).
|
|
254
|
+
|
|
255
|
+ """
|
|
256
|
+ self.debuglevel = debuglevel
|
|
257
|
+
|
|
258
|
+ def close(self):
|
|
259
|
+ """Close the connection."""
|
|
260
|
+ if self.sock:
|
|
261
|
+ self.sock.close()
|
|
262
|
+ self.sock = 0
|
|
263
|
+ self.eof = 1
|
|
264
|
+ self.iacseq = ''
|
|
265
|
+ self.sb = 0
|
|
266
|
+
|
|
267
|
+ def get_socket(self):
|
|
268
|
+ """Return the socket object used internally."""
|
|
269
|
+ return self.sock
|
|
270
|
+
|
|
271
|
+ def fileno(self):
|
|
272
|
+ """Return the fileno() of the socket object used internally."""
|
|
273
|
+ return self.sock.fileno()
|
|
274
|
+
|
|
275
|
+ def write(self, buffer):
|
|
276
|
+ """Write a string to the socket, doubling any IAC characters.
|
|
277
|
+
|
|
278
|
+ Can block if the connection is blocked. May raise
|
|
279
|
+ socket.error if the connection is closed.
|
|
280
|
+
|
|
281
|
+ """
|
|
282
|
+ if IAC in buffer:
|
|
283
|
+ buffer = buffer.replace(IAC, IAC+IAC)
|
|
284
|
+ self.msg("send %r", buffer)
|
|
285
|
+ self.sock.sendall(buffer)
|
|
286
|
+
|
|
287
|
+ def read_until(self, match, timeout=None):
|
|
288
|
+ """Read until a given string is encountered or until timeout.
|
|
289
|
+
|
|
290
|
+ When no match is found, return whatever is available instead,
|
|
291
|
+ possibly the empty string. Raise EOFError if the connection
|
|
292
|
+ is closed and no cooked data is available.
|
|
293
|
+
|
|
294
|
+ """
|
|
295
|
+ if self._has_poll:
|
|
296
|
+ return self._read_until_with_poll(match, timeout)
|
|
297
|
+ else:
|
|
298
|
+ return self._read_until_with_select(match, timeout)
|
|
299
|
+
|
|
300
|
+ def _read_until_with_poll(self, match, timeout):
|
|
301
|
+ """Read until a given string is encountered or until timeout.
|
|
302
|
+
|
|
303
|
+ This method uses select.poll() to implement the timeout.
|
|
304
|
+ """
|
|
305
|
+ n = len(match)
|
|
306
|
+ call_timeout = timeout
|
|
307
|
+ if timeout is not None:
|
|
308
|
+ from time import time
|
|
309
|
+ time_start = time()
|
|
310
|
+ self.process_rawq()
|
|
311
|
+ i = self.cookedq.find(match)
|
|
312
|
+ if i < 0:
|
|
313
|
+ poller = select.poll()
|
|
314
|
+ poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
|
|
315
|
+ poller.register(self, poll_in_or_priority_flags)
|
|
316
|
+ while i < 0 and not self.eof:
|
|
317
|
+ try:
|
|
318
|
+ # Poll takes its timeout in milliseconds.
|
|
319
|
+ ready = poller.poll(None if timeout is None
|
|
320
|
+ else 1000 * call_timeout)
|
|
321
|
+ except select.error as e:
|
|
322
|
+ if e.errno == errno.EINTR:
|
|
323
|
+ if timeout is not None:
|
|
324
|
+ elapsed = time() - time_start
|
|
325
|
+ call_timeout = timeout-elapsed
|
|
326
|
+ continue
|
|
327
|
+ raise
|
|
328
|
+ for fd, mode in ready:
|
|
329
|
+ if mode & poll_in_or_priority_flags:
|
|
330
|
+ i = max(0, len(self.cookedq)-n)
|
|
331
|
+ self.fill_rawq()
|
|
332
|
+ self.process_rawq()
|
|
333
|
+ i = self.cookedq.find(match, i)
|
|
334
|
+ if timeout is not None:
|
|
335
|
+ elapsed = time() - time_start
|
|
336
|
+ if elapsed >= timeout:
|
|
337
|
+ break
|
|
338
|
+ call_timeout = timeout-elapsed
|
|
339
|
+ poller.unregister(self)
|
|
340
|
+ if i >= 0:
|
|
341
|
+ i = i + n
|
|
342
|
+ buf = self.cookedq[:i]
|
|
343
|
+ self.cookedq = self.cookedq[i:]
|
|
344
|
+ return buf
|
|
345
|
+ return self.read_very_lazy()
|
|
346
|
+
|
|
347
|
+ def _read_until_with_select(self, match, timeout=None):
|
|
348
|
+ """Read until a given string is encountered or until timeout.
|
|
349
|
+
|
|
350
|
+ The timeout is implemented using select.select().
|
|
351
|
+ """
|
|
352
|
+ n = len(match)
|
|
353
|
+ self.process_rawq()
|
|
354
|
+ i = self.cookedq.find(match)
|
|
355
|
+ if i >= 0:
|
|
356
|
+ i = i+n
|
|
357
|
+ buf = self.cookedq[:i]
|
|
358
|
+ self.cookedq = self.cookedq[i:]
|
|
359
|
+ return buf
|
|
360
|
+ s_reply = ([self], [], [])
|
|
361
|
+ s_args = s_reply
|
|
362
|
+ if timeout is not None:
|
|
363
|
+ s_args = s_args + (timeout,)
|
|
364
|
+ from time import time
|
|
365
|
+ time_start = time()
|
|
366
|
+ while not self.eof and select.select(*s_args) == s_reply:
|
|
367
|
+ i = max(0, len(self.cookedq)-n)
|
|
368
|
+ self.fill_rawq()
|
|
369
|
+ self.process_rawq()
|
|
370
|
+ i = self.cookedq.find(match, i)
|
|
371
|
+ if i >= 0:
|
|
372
|
+ i = i+n
|
|
373
|
+ buf = self.cookedq[:i]
|
|
374
|
+ self.cookedq = self.cookedq[i:]
|
|
375
|
+ return buf
|
|
376
|
+ if timeout is not None:
|
|
377
|
+ elapsed = time() - time_start
|
|
378
|
+ if elapsed >= timeout:
|
|
379
|
+ break
|
|
380
|
+ s_args = s_reply + (timeout-elapsed,)
|
|
381
|
+ return self.read_very_lazy()
|
|
382
|
+
|
|
383
|
+ def read_all(self):
|
|
384
|
+ """Read all data until EOF; block until connection closed."""
|
|
385
|
+ self.process_rawq()
|
|
386
|
+ while not self.eof:
|
|
387
|
+ self.fill_rawq()
|
|
388
|
+ self.process_rawq()
|
|
389
|
+ buf = self.cookedq
|
|
390
|
+ self.cookedq = ''
|
|
391
|
+ return buf
|
|
392
|
+
|
|
393
|
+ def read_some(self):
|
|
394
|
+ """Read at least one byte of cooked data unless EOF is hit.
|
|
395
|
+
|
|
396
|
+ Return '' if EOF is hit. Block if no data is immediately
|
|
397
|
+ available.
|
|
398
|
+
|
|
399
|
+ """
|
|
400
|
+ self.process_rawq()
|
|
401
|
+ while not self.cookedq and not self.eof:
|
|
402
|
+ self.fill_rawq()
|
|
403
|
+ self.process_rawq()
|
|
404
|
+ buf = self.cookedq
|
|
405
|
+ self.cookedq = ''
|
|
406
|
+ return buf
|
|
407
|
+
|
|
408
|
+ def read_very_eager(self):
|
|
409
|
+ """Read everything that's possible without blocking in I/O (eager).
|
|
410
|
+
|
|
411
|
+ Raise EOFError if connection closed and no cooked data
|
|
412
|
+ available. Return '' if no cooked data available otherwise.
|
|
413
|
+ Don't block unless in the midst of an IAC sequence.
|
|
414
|
+
|
|
415
|
+ """
|
|
416
|
+ self.process_rawq()
|
|
417
|
+ while not self.eof and self.sock_avail():
|
|
418
|
+ self.fill_rawq()
|
|
419
|
+ self.process_rawq()
|
|
420
|
+ return self.read_very_lazy()
|
|
421
|
+
|
|
422
|
+ def read_eager(self):
|
|
423
|
+ """Read readily available data.
|
|
424
|
+
|
|
425
|
+ Raise EOFError if connection closed and no cooked data
|
|
426
|
+ available. Return '' if no cooked data available otherwise.
|
|
427
|
+ Don't block unless in the midst of an IAC sequence.
|
|
428
|
+
|
|
429
|
+ """
|
|
430
|
+ self.process_rawq()
|
|
431
|
+ while not self.cookedq and not self.eof and self.sock_avail():
|
|
432
|
+ self.fill_rawq()
|
|
433
|
+ self.process_rawq()
|
|
434
|
+ return self.read_very_lazy()
|
|
435
|
+
|
|
436
|
+ def read_lazy(self):
|
|
437
|
+ """Process and return data that's already in the queues (lazy).
|
|
438
|
+
|
|
439
|
+ Raise EOFError if connection closed and no data available.
|
|
440
|
+ Return '' if no cooked data available otherwise. Don't block
|
|
441
|
+ unless in the midst of an IAC sequence.
|
|
442
|
+
|
|
443
|
+ """
|
|
444
|
+ self.process_rawq()
|
|
445
|
+ return self.read_very_lazy()
|
|
446
|
+
|
|
447
|
+ def read_very_lazy(self):
|
|
448
|
+ """Return any data available in the cooked queue (very lazy).
|
|
449
|
+
|
|
450
|
+ Raise EOFError if connection closed and no data available.
|
|
451
|
+ Return '' if no cooked data available otherwise. Don't block.
|
|
452
|
+
|
|
453
|
+ """
|
|
454
|
+ buf = self.cookedq
|
|
455
|
+ self.cookedq = ''
|
|
456
|
+ if not buf and self.eof and not self.rawq:
|
|
457
|
+ raise EOFError, 'telnet connection closed'
|
|
458
|
+ return buf
|
|
459
|
+
|
|
460
|
+ def read_sb_data(self):
|
|
461
|
+ """Return any data available in the SB ... SE queue.
|
|
462
|
+
|
|
463
|
+ Return '' if no SB ... SE available. Should only be called
|
|
464
|
+ after seeing a SB or SE command. When a new SB command is
|
|
465
|
+ found, old unread SB data will be discarded. Don't block.
|
|
466
|
+
|
|
467
|
+ """
|
|
468
|
+ buf = self.sbdataq
|
|
469
|
+ self.sbdataq = ''
|
|
470
|
+ return buf
|
|
471
|
+
|
|
472
|
+ def set_option_negotiation_callback(self, callback):
|
|
473
|
+ """Provide a callback function called after each receipt of a telnet option."""
|
|
474
|
+ self.option_callback = callback
|
|
475
|
+
|
|
476
|
+ def process_rawq(self):
|
|
477
|
+ """Transfer from raw queue to cooked queue.
|
|
478
|
+
|
|
479
|
+ Set self.eof when connection is closed. Don't block unless in
|
|
480
|
+ the midst of an IAC sequence.
|
|
481
|
+
|
|
482
|
+ """
|
|
483
|
+ buf = ['', '']
|
|
484
|
+ try:
|
|
485
|
+ while self.rawq:
|
|
486
|
+ c = self.rawq_getchar()
|
|
487
|
+ if not self.iacseq:
|
|
488
|
+ #if c == theNULL:
|
|
489
|
+ # continue
|
|
490
|
+ #if c == "\021":
|
|
491
|
+ # continue
|
|
492
|
+ if c != IAC:
|
|
493
|
+ buf[self.sb] = buf[self.sb] + c
|
|
494
|
+ continue
|
|
495
|
+ else:
|
|
496
|
+ self.iacseq += c
|
|
497
|
+ elif len(self.iacseq) == 1:
|
|
498
|
+ # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'
|
|
499
|
+ if c in (DO, DONT, WILL, WONT):
|
|
500
|
+ self.iacseq += c
|
|
501
|
+ continue
|
|
502
|
+
|
|
503
|
+ self.iacseq = ''
|
|
504
|
+ if c == IAC:
|
|
505
|
+ buf[self.sb] = buf[self.sb] + c
|
|
506
|
+ else:
|
|
507
|
+ if c == SB: # SB ... SE start.
|
|
508
|
+ self.sb = 1
|
|
509
|
+ self.sbdataq = ''
|
|
510
|
+ elif c == SE:
|
|
511
|
+ self.sb = 0
|
|
512
|
+ self.sbdataq = self.sbdataq + buf[1]
|
|
513
|
+ buf[1] = ''
|
|
514
|
+ if self.option_callback:
|
|
515
|
+ # Callback is supposed to look into
|
|
516
|
+ # the sbdataq
|
|
517
|
+ self.option_callback(self.sock, c, NOOPT)
|
|
518
|
+ else:
|
|
519
|
+ # We can't offer automatic processing of
|
|
520
|
+ # suboptions. Alas, we should not get any
|
|
521
|
+ # unless we did a WILL/DO before.
|
|
522
|
+ self.msg('IAC %d not recognized' % ord(c))
|
|
523
|
+ elif len(self.iacseq) == 2:
|
|
524
|
+ cmd = self.iacseq[1]
|
|
525
|
+ self.iacseq = ''
|
|
526
|
+ opt = c
|
|
527
|
+ if cmd in (DO, DONT):
|
|
528
|
+ self.msg('IAC %s %d',
|
|
529
|
+ cmd == DO and 'DO' or 'DONT', ord(opt))
|
|
530
|
+ if self.option_callback:
|
|
531
|
+ self.option_callback(self.sock, cmd, opt)
|
|
532
|
+ else:
|
|
533
|
+ self.sock.sendall(IAC + WONT + opt)
|
|
534
|
+ elif cmd in (WILL, WONT):
|
|
535
|
+ self.msg('IAC %s %d',
|
|
536
|
+ cmd == WILL and 'WILL' or 'WONT', ord(opt))
|
|
537
|
+ if self.option_callback:
|
|
538
|
+ self.option_callback(self.sock, cmd, opt)
|
|
539
|
+ else:
|
|
540
|
+ self.sock.sendall(IAC + DONT + opt)
|
|
541
|
+ except EOFError: # raised by self.rawq_getchar()
|
|
542
|
+ self.iacseq = '' # Reset on EOF
|
|
543
|
+ self.sb = 0
|
|
544
|
+ pass
|
|
545
|
+ self.cookedq = self.cookedq + buf[0]
|
|
546
|
+ self.sbdataq = self.sbdataq + buf[1]
|
|
547
|
+
|
|
548
|
+ def rawq_getchar(self):
|
|
549
|
+ """Get next char from raw queue.
|
|
550
|
+
|
|
551
|
+ Block if no data is immediately available. Raise EOFError
|
|
552
|
+ when connection is closed.
|
|
553
|
+
|
|
554
|
+ """
|
|
555
|
+ if not self.rawq:
|
|
556
|
+ self.fill_rawq()
|
|
557
|
+ if self.eof:
|
|
558
|
+ raise EOFError
|
|
559
|
+ c = self.rawq[self.irawq]
|
|
560
|
+ self.irawq = self.irawq + 1
|
|
561
|
+ if self.irawq >= len(self.rawq):
|
|
562
|
+ self.rawq = ''
|
|
563
|
+ self.irawq = 0
|
|
564
|
+ return c
|
|
565
|
+
|
|
566
|
+ def fill_rawq(self):
|
|
567
|
+ """Fill raw queue from exactly one recv() system call.
|
|
568
|
+
|
|
569
|
+ Block if no data is immediately available. Set self.eof when
|
|
570
|
+ connection is closed.
|
|
571
|
+
|
|
572
|
+ """
|
|
573
|
+ if self.irawq >= len(self.rawq):
|
|
574
|
+ self.rawq = ''
|
|
575
|
+ self.irawq = 0
|
|
576
|
+ # The buffer size should be fairly small so as to avoid quadratic
|
|
577
|
+ # behavior in process_rawq() above
|
|
578
|
+ buf = self.sock.recv(50)
|
|
579
|
+ self.msg("recv %r", buf)
|
|
580
|
+ self.eof = (not buf)
|
|
581
|
+ self.rawq = self.rawq + buf
|
|
582
|
+
|
|
583
|
+ def sock_avail(self):
|
|
584
|
+ """Test whether data is available on the socket."""
|
|
585
|
+ return select.select([self], [], [], 0) == ([self], [], [])
|
|
586
|
+
|
|
587
|
+ def interact(self):
|
|
588
|
+ """Interaction function, emulates a very dumb telnet client."""
|
|
589
|
+ if sys.platform == "win32":
|
|
590
|
+ self.mt_interact()
|
|
591
|
+ return
|
|
592
|
+ while 1:
|
|
593
|
+ rfd, wfd, xfd = select.select([self, sys.stdin], [], [])
|
|
594
|
+ if self in rfd:
|
|
595
|
+ try:
|
|
596
|
+ text = self.read_eager()
|
|
597
|
+ except EOFError:
|
|
598
|
+ print '*** Connection closed by remote host ***'
|
|
599
|
+ break
|
|
600
|
+ if text:
|
|
601
|
+ sys.stdout.write(text)
|
|
602
|
+ sys.stdout.flush()
|
|
603
|
+ if sys.stdin in rfd:
|
|
604
|
+ line = sys.stdin.readline()
|
|
605
|
+ if not line:
|
|
606
|
+ break
|
|
607
|
+ self.write(line)
|
|
608
|
+
|
|
609
|
+ def mt_interact(self):
|
|
610
|
+ """Multithreaded version of interact()."""
|
|
611
|
+ import thread
|
|
612
|
+ thread.start_new_thread(self.listener, ())
|
|
613
|
+ while 1:
|
|
614
|
+ line = sys.stdin.readline()
|
|
615
|
+ if not line:
|
|
616
|
+ break
|
|
617
|
+ self.write(line)
|
|
618
|
+
|
|
619
|
+ def listener(self):
|
|
620
|
+ """Helper for mt_interact() -- this executes in the other thread."""
|
|
621
|
+ while 1:
|
|
622
|
+ try:
|
|
623
|
+ data = self.read_eager()
|
|
624
|
+ except EOFError:
|
|
625
|
+ print '*** Connection closed by remote host ***'
|
|
626
|
+ return
|
|
627
|
+ if data:
|
|
628
|
+ sys.stdout.write(data)
|
|
629
|
+ else:
|
|
630
|
+ sys.stdout.flush()
|
|
631
|
+
|
|
632
|
+ def expect(self, list, timeout=None):
|
|
633
|
+ """Read until one from a list of a regular expressions matches.
|
|
634
|
+
|
|
635
|
+ The first argument is a list of regular expressions, either
|
|
636
|
+ compiled (re.RegexObject instances) or uncompiled (strings).
|
|
637
|
+ The optional second argument is a timeout, in seconds; default
|
|
638
|
+ is no timeout.
|
|
639
|
+
|
|
640
|
+ Return a tuple of three items: the index in the list of the
|
|
641
|
+ first regular expression that matches; the match object
|
|
642
|
+ returned; and the text read up till and including the match.
|
|
643
|
+
|
|
644
|
+ If EOF is read and no text was read, raise EOFError.
|
|
645
|
+ Otherwise, when nothing matches, return (-1, None, text) where
|
|
646
|
+ text is the text received so far (may be the empty string if a
|
|
647
|
+ timeout happened).
|
|
648
|
+
|
|
649
|
+ If a regular expression ends with a greedy match (e.g. '.*')
|
|
650
|
+ or if more than one expression can match the same input, the
|
|
651
|
+ results are undeterministic, and may depend on the I/O timing.
|
|
652
|
+
|
|
653
|
+ """
|
|
654
|
+ if self._has_poll:
|
|
655
|
+ return self._expect_with_poll(list, timeout)
|
|
656
|
+ else:
|
|
657
|
+ return self._expect_with_select(list, timeout)
|
|
658
|
+
|
|
659
|
+ def _expect_with_poll(self, expect_list, timeout=None):
|
|
660
|
+ """Read until one from a list of a regular expressions matches.
|
|
661
|
+
|
|
662
|
+ This method uses select.poll() to implement the timeout.
|
|
663
|
+ """
|
|
664
|
+ re = None
|
|
665
|
+ expect_list = expect_list[:]
|
|
666
|
+ indices = range(len(expect_list))
|
|
667
|
+ for i in indices:
|
|
668
|
+ if not hasattr(expect_list[i], "search"):
|
|
669
|
+ if not re: import re
|
|
670
|
+ expect_list[i] = re.compile(expect_list[i])
|
|
671
|
+ call_timeout = timeout
|
|
672
|
+ if timeout is not None:
|
|
673
|
+ from time import time
|
|
674
|
+ time_start = time()
|
|
675
|
+ self.process_rawq()
|
|
676
|
+ m = None
|
|
677
|
+ for i in indices:
|
|
678
|
+ m = expect_list[i].search(self.cookedq)
|
|
679
|
+ if m:
|
|
680
|
+ e = m.end()
|
|
681
|
+ text = self.cookedq[:e]
|
|
682
|
+ self.cookedq = self.cookedq[e:]
|
|
683
|
+ break
|
|
684
|
+ if not m:
|
|
685
|
+ poller = select.poll()
|
|
686
|
+ poll_in_or_priority_flags = select.POLLIN | select.POLLPRI
|
|
687
|
+ poller.register(self, poll_in_or_priority_flags)
|
|
688
|
+ while not m and not self.eof:
|
|
689
|
+ try:
|
|
690
|
+ ready = poller.poll(None if timeout is None
|
|
691
|
+ else 1000 * call_timeout)
|
|
692
|
+ except select.error as e:
|
|
693
|
+ if e.errno == errno.EINTR:
|
|
694
|
+ if timeout is not None:
|
|
695
|
+ elapsed = time() - time_start
|
|
696
|
+ call_timeout = timeout-elapsed
|
|
697
|
+ continue
|
|
698
|
+ raise
|
|
699
|
+ for fd, mode in ready:
|
|
700
|
+ if mode & poll_in_or_priority_flags:
|
|
701
|
+ self.fill_rawq()
|
|
702
|
+ self.process_rawq()
|
|
703
|
+ for i in indices:
|
|
704
|
+ m = expect_list[i].search(self.cookedq)
|
|
705
|
+ if m:
|
|
706
|
+ e = m.end()
|
|
707
|
+ text = self.cookedq[:e]
|
|
708
|
+ self.cookedq = self.cookedq[e:]
|
|
709
|
+ break
|
|
710
|
+ if timeout is not None:
|
|
711
|
+ elapsed = time() - time_start
|
|
712
|
+ if elapsed >= timeout:
|
|
713
|
+ break
|
|
714
|
+ call_timeout = timeout-elapsed
|
|
715
|
+ poller.unregister(self)
|
|
716
|
+ if m:
|
|
717
|
+ return (i, m, text)
|
|
718
|
+ text = self.read_very_lazy()
|
|
719
|
+ if not text and self.eof:
|
|
720
|
+ raise EOFError
|
|
721
|
+ return (-1, None, text)
|
|
722
|
+
|
|
723
|
+ def _expect_with_select(self, list, timeout=None):
|
|
724
|
+ """Read until one from a list of a regular expressions matches.
|
|
725
|
+
|
|
726
|
+ The timeout is implemented using select.select().
|
|
727
|
+ """
|
|
728
|
+ re = None
|
|
729
|
+ list = list[:]
|
|
730
|
+ indices = range(len(list))
|
|
731
|
+ for i in indices:
|
|
732
|
+ if not hasattr(list[i], "search"):
|
|
733
|
+ if not re: import re
|
|
734
|
+ list[i] = re.compile(list[i])
|
|
735
|
+ if timeout is not None:
|
|
736
|
+ from time import time
|
|
737
|
+ time_start = time()
|
|
738
|
+ while 1:
|
|
739
|
+ self.process_rawq()
|
|
740
|
+ for i in indices:
|
|
741
|
+ m = list[i].search(self.cookedq)
|
|
742
|
+ if m:
|
|
743
|
+ e = m.end()
|
|
744
|
+ text = self.cookedq[:e]
|
|
745
|
+ self.cookedq = self.cookedq[e:]
|
|
746
|
+ return (i, m, text)
|
|
747
|
+ if self.eof:
|
|
748
|
+ break
|
|
749
|
+ if timeout is not None:
|
|
750
|
+ elapsed = time() - time_start
|
|
751
|
+ if elapsed >= timeout:
|
|
752
|
+ break
|
|
753
|
+ s_args = ([self.fileno()], [], [], timeout-elapsed)
|
|
754
|
+ r, w, x = select.select(*s_args)
|
|
755
|
+ if not r:
|
|
756
|
+ break
|
|
757
|
+ self.fill_rawq()
|
|
758
|
+ text = self.read_very_lazy()
|
|
759
|
+ if not text and self.eof:
|
|
760
|
+ raise EOFError
|
|
761
|
+ return (-1, None, text)
|
|
762
|
+
|
|
763
|
+
|
|
764
|
+def test():
|
|
765
|
+ """Test program for telnetlib.
|
|
766
|
+
|
|
767
|
+ Usage: python telnetlib.py [-d] ... [host [port]]
|
|
768
|
+
|
|
769
|
+ Default host is localhost; default port is 23.
|
|
770
|
+
|
|
771
|
+ """
|
|
772
|
+ debuglevel = 0
|
|
773
|
+ while sys.argv[1:] and sys.argv[1] == '-d':
|
|
774
|
+ debuglevel = debuglevel+1
|
|
775
|
+ del sys.argv[1]
|
|
776
|
+ host = 'localhost'
|
|
777
|
+ if sys.argv[1:]:
|
|
778
|
+ host = sys.argv[1]
|
|
779
|
+ port = 0
|
|
780
|
+ if sys.argv[2:]:
|
|
781
|
+ portstr = sys.argv[2]
|
|
782
|
+ try:
|
|
783
|
+ port = int(portstr)
|
|
784
|
+ except ValueError:
|
|
785
|
+ port = socket.getservbyname(portstr, 'tcp')
|
|
786
|
+ tn = Telnet()
|
|
787
|
+ tn.set_debuglevel(debuglevel)
|
|
788
|
+ tn.open(host, port, timeout=0.5)
|
|
789
|
+ tn.interact()
|
|
790
|
+ tn.close()
|
|
791
|
+
|
|
792
|
+if __name__ == '__main__':
|
|
793
|
+ test()
|