Debian Codegraph @

lib/jnpr/junos/transport/_telnetlib/telnetlib.py

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