home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / lib / python2.5 / telnetlib.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2008-10-29  |  19.6 KB  |  746 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.5)
  3.  
  4. '''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. import sys
  38. import socket
  39. import select
  40. __all__ = [
  41.     'Telnet']
  42. DEBUGLEVEL = 0
  43. TELNET_PORT = 23
  44. IAC = chr(255)
  45. DONT = chr(254)
  46. DO = chr(253)
  47. WONT = chr(252)
  48. WILL = chr(251)
  49. theNULL = chr(0)
  50. SE = chr(240)
  51. NOP = chr(241)
  52. DM = chr(242)
  53. BRK = chr(243)
  54. IP = chr(244)
  55. AO = chr(245)
  56. AYT = chr(246)
  57. EC = chr(247)
  58. EL = chr(248)
  59. GA = chr(249)
  60. SB = chr(250)
  61. BINARY = chr(0)
  62. ECHO = chr(1)
  63. RCP = chr(2)
  64. SGA = chr(3)
  65. NAMS = chr(4)
  66. STATUS = chr(5)
  67. TM = chr(6)
  68. RCTE = chr(7)
  69. NAOL = chr(8)
  70. NAOP = chr(9)
  71. NAOCRD = chr(10)
  72. NAOHTS = chr(11)
  73. NAOHTD = chr(12)
  74. NAOFFD = chr(13)
  75. NAOVTS = chr(14)
  76. NAOVTD = chr(15)
  77. NAOLFD = chr(16)
  78. XASCII = chr(17)
  79. LOGOUT = chr(18)
  80. BM = chr(19)
  81. DET = chr(20)
  82. SUPDUP = chr(21)
  83. SUPDUPOUTPUT = chr(22)
  84. SNDLOC = chr(23)
  85. TTYPE = chr(24)
  86. EOR = chr(25)
  87. TUID = chr(26)
  88. OUTMRK = chr(27)
  89. TTYLOC = chr(28)
  90. VT3270REGIME = chr(29)
  91. X3PAD = chr(30)
  92. NAWS = chr(31)
  93. TSPEED = chr(32)
  94. LFLOW = chr(33)
  95. LINEMODE = chr(34)
  96. XDISPLOC = chr(35)
  97. OLD_ENVIRON = chr(36)
  98. AUTHENTICATION = chr(37)
  99. ENCRYPT = chr(38)
  100. NEW_ENVIRON = chr(39)
  101. TN3270E = chr(40)
  102. XAUTH = chr(41)
  103. CHARSET = chr(42)
  104. RSP = chr(43)
  105. COM_PORT_OPTION = chr(44)
  106. SUPPRESS_LOCAL_ECHO = chr(45)
  107. TLS = chr(46)
  108. KERMIT = chr(47)
  109. SEND_URL = chr(48)
  110. FORWARD_X = chr(49)
  111. PRAGMA_LOGON = chr(138)
  112. SSPI_LOGON = chr(139)
  113. PRAGMA_HEARTBEAT = chr(140)
  114. EXOPL = chr(255)
  115. NOOPT = chr(0)
  116.  
  117. class Telnet:
  118.     """Telnet interface class.
  119.  
  120.     An instance of this class represents a connection to a telnet
  121.     server.  The instance is initially not connected; the open()
  122.     method must be used to establish a connection.  Alternatively, the
  123.     host name and optional port number can be passed to the
  124.     constructor, too.
  125.  
  126.     Don't try to reopen an already connected instance.
  127.  
  128.     This class has many read_*() methods.  Note that some of them
  129.     raise EOFError when the end of the connection is read, because
  130.     they can return an empty string for other reasons.  See the
  131.     individual doc strings.
  132.  
  133.     read_until(expected, [timeout])
  134.         Read until the expected string has been seen, or a timeout is
  135.         hit (default is no timeout); may block.
  136.  
  137.     read_all()
  138.         Read all data until EOF; may block.
  139.  
  140.     read_some()
  141.         Read at least one byte or EOF; may block.
  142.  
  143.     read_very_eager()
  144.         Read all data available already queued or on the socket,
  145.         without blocking.
  146.  
  147.     read_eager()
  148.         Read either data already queued or some data available on the
  149.         socket, without blocking.
  150.  
  151.     read_lazy()
  152.         Read all data in the raw queue (processing it first), without
  153.         doing any socket I/O.
  154.  
  155.     read_very_lazy()
  156.         Reads all data in the cooked queue, without doing any socket
  157.         I/O.
  158.  
  159.     read_sb_data()
  160.         Reads available data between SB ... SE sequence. Don't block.
  161.  
  162.     set_option_negotiation_callback(callback)
  163.         Each time a telnet option is read on the input flow, this callback
  164.         (if set) is called with the following parameters :
  165.         callback(telnet socket, command, option)
  166.             option will be chr(0) when there is no option.
  167.         No other action is done afterwards by telnetlib.
  168.  
  169.     """
  170.     
  171.     def __init__(self, host = None, port = 0):
  172.         '''Constructor.
  173.  
  174.         When called without arguments, create an unconnected instance.
  175.         With a hostname argument, it connects the instance; a port
  176.         number is optional.
  177.  
  178.         '''
  179.         self.debuglevel = DEBUGLEVEL
  180.         self.host = host
  181.         self.port = port
  182.         self.sock = None
  183.         self.rawq = ''
  184.         self.irawq = 0
  185.         self.cookedq = ''
  186.         self.eof = 0
  187.         self.iacseq = ''
  188.         self.sb = 0
  189.         self.sbdataq = ''
  190.         self.option_callback = None
  191.         if host is not None:
  192.             self.open(host, port)
  193.         
  194.  
  195.     
  196.     def open(self, host, port = 0):
  197.         """Connect to a host.
  198.  
  199.         The optional second argument is the port number, which
  200.         defaults to the standard telnet port (23).
  201.  
  202.         Don't try to reopen an already connected instance.
  203.  
  204.         """
  205.         self.eof = 0
  206.         if not port:
  207.             port = TELNET_PORT
  208.         
  209.         self.host = host
  210.         self.port = port
  211.         msg = 'getaddrinfo returns an empty list'
  212.         for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):
  213.             (af, socktype, proto, canonname, sa) = res
  214.             
  215.             try:
  216.                 self.sock = socket.socket(af, socktype, proto)
  217.                 self.sock.connect(sa)
  218.             except socket.error:
  219.                 msg = None
  220.                 if self.sock:
  221.                     self.sock.close()
  222.                 
  223.                 self.sock = None
  224.                 continue
  225.  
  226.         
  227.         if not self.sock:
  228.             raise socket.error, msg
  229.         
  230.  
  231.     
  232.     def __del__(self):
  233.         '''Destructor -- close the connection.'''
  234.         self.close()
  235.  
  236.     
  237.     def msg(self, msg, *args):
  238.         '''Print a debug message, when the debug level is > 0.
  239.  
  240.         If extra arguments are present, they are substituted in the
  241.         message using the standard string formatting operator.
  242.  
  243.         '''
  244.         if self.debuglevel > 0:
  245.             print 'Telnet(%s,%d):' % (self.host, self.port),
  246.             if args:
  247.                 print msg % args
  248.             else:
  249.                 print msg
  250.         
  251.  
  252.     
  253.     def set_debuglevel(self, debuglevel):
  254.         '''Set the debug level.
  255.  
  256.         The higher it is, the more debug output you get (on sys.stdout).
  257.  
  258.         '''
  259.         self.debuglevel = debuglevel
  260.  
  261.     
  262.     def close(self):
  263.         '''Close the connection.'''
  264.         if self.sock:
  265.             self.sock.close()
  266.         
  267.         self.sock = 0
  268.         self.eof = 1
  269.         self.iacseq = ''
  270.         self.sb = 0
  271.  
  272.     
  273.     def get_socket(self):
  274.         '''Return the socket object used internally.'''
  275.         return self.sock
  276.  
  277.     
  278.     def fileno(self):
  279.         '''Return the fileno() of the socket object used internally.'''
  280.         return self.sock.fileno()
  281.  
  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.         socket.error if the connection is closed.
  288.  
  289.         '''
  290.         if IAC in buffer:
  291.             buffer = buffer.replace(IAC, IAC + IAC)
  292.         
  293.         self.msg('send %r', buffer)
  294.         self.sock.sendall(buffer)
  295.  
  296.     
  297.     def read_until(self, match, timeout = None):
  298.         '''Read until a given string is encountered or until timeout.
  299.  
  300.         When no match is found, return whatever is available instead,
  301.         possibly the empty string.  Raise EOFError if the connection
  302.         is closed and no cooked data is available.
  303.  
  304.         '''
  305.         n = len(match)
  306.         self.process_rawq()
  307.         i = self.cookedq.find(match)
  308.         if i >= 0:
  309.             i = i + n
  310.             buf = self.cookedq[:i]
  311.             self.cookedq = self.cookedq[i:]
  312.             return buf
  313.         
  314.         s_reply = ([
  315.             self], [], [])
  316.         s_args = s_reply
  317.         if timeout is not None:
  318.             s_args = s_args + (timeout,)
  319.             time = time
  320.             import time
  321.             time_start = time()
  322.         
  323.         while not (self.eof) and select.select(*s_args) == s_reply:
  324.             i = max(0, len(self.cookedq) - n)
  325.             self.fill_rawq()
  326.             self.process_rawq()
  327.             i = self.cookedq.find(match, i)
  328.             if i >= 0:
  329.                 i = i + n
  330.                 buf = self.cookedq[:i]
  331.                 self.cookedq = self.cookedq[i:]
  332.                 return buf
  333.             
  334.             if timeout is not None:
  335.                 elapsed = time() - time_start
  336.                 if elapsed >= timeout:
  337.                     break
  338.                 
  339.                 s_args = s_reply + (timeout - elapsed,)
  340.                 continue
  341.         return self.read_very_lazy()
  342.  
  343.     
  344.     def read_all(self):
  345.         '''Read all data until EOF; block until connection closed.'''
  346.         self.process_rawq()
  347.         while not self.eof:
  348.             self.fill_rawq()
  349.             self.process_rawq()
  350.         buf = self.cookedq
  351.         self.cookedq = ''
  352.         return buf
  353.  
  354.     
  355.     def read_some(self):
  356.         """Read at least one byte of cooked data unless EOF is hit.
  357.  
  358.         Return '' if EOF is hit.  Block if no data is immediately
  359.         available.
  360.  
  361.         """
  362.         self.process_rawq()
  363.         while not (self.cookedq) and not (self.eof):
  364.             self.fill_rawq()
  365.             self.process_rawq()
  366.         buf = self.cookedq
  367.         self.cookedq = ''
  368.         return buf
  369.  
  370.     
  371.     def read_very_eager(self):
  372.         """Read everything that's possible without blocking in I/O (eager).
  373.  
  374.         Raise EOFError if connection closed and no cooked data
  375.         available.  Return '' if no cooked data available otherwise.
  376.         Don't block unless in the midst of an IAC sequence.
  377.  
  378.         """
  379.         self.process_rawq()
  380.         while not (self.eof) and self.sock_avail():
  381.             self.fill_rawq()
  382.             self.process_rawq()
  383.         return self.read_very_lazy()
  384.  
  385.     
  386.     def read_eager(self):
  387.         """Read readily available data.
  388.  
  389.         Raise EOFError if connection closed and no cooked data
  390.         available.  Return '' if no cooked data available otherwise.
  391.         Don't block unless in the midst of an IAC sequence.
  392.  
  393.         """
  394.         self.process_rawq()
  395.         while not (self.cookedq) and not (self.eof) and self.sock_avail():
  396.             self.fill_rawq()
  397.             self.process_rawq()
  398.         return self.read_very_lazy()
  399.  
  400.     
  401.     def read_lazy(self):
  402.         """Process and return data that's already in the queues (lazy).
  403.  
  404.         Raise EOFError if connection closed and no data available.
  405.         Return '' if no cooked data available otherwise.  Don't block
  406.         unless in the midst of an IAC sequence.
  407.  
  408.         """
  409.         self.process_rawq()
  410.         return self.read_very_lazy()
  411.  
  412.     
  413.     def read_very_lazy(self):
  414.         """Return any data available in the cooked queue (very lazy).
  415.  
  416.         Raise EOFError if connection closed and no data available.
  417.         Return '' if no cooked data available otherwise.  Don't block.
  418.  
  419.         """
  420.         buf = self.cookedq
  421.         self.cookedq = ''
  422.         if not buf and self.eof and not (self.rawq):
  423.             raise EOFError, 'telnet connection closed'
  424.         
  425.         return buf
  426.  
  427.     
  428.     def read_sb_data(self):
  429.         """Return any data available in the SB ... SE queue.
  430.  
  431.         Return '' if no SB ... SE available. Should only be called
  432.         after seeing a SB or SE command. When a new SB command is
  433.         found, old unread SB data will be discarded. Don't block.
  434.  
  435.         """
  436.         buf = self.sbdataq
  437.         self.sbdataq = ''
  438.         return buf
  439.  
  440.     
  441.     def set_option_negotiation_callback(self, callback):
  442.         '''Provide a callback function called after each receipt of a telnet option.'''
  443.         self.option_callback = callback
  444.  
  445.     
  446.     def process_rawq(self):
  447.         """Transfer from raw queue to cooked queue.
  448.  
  449.         Set self.eof when connection is closed.  Don't block unless in
  450.         the midst of an IAC sequence.
  451.  
  452.         """
  453.         buf = [
  454.             '',
  455.             '']
  456.         
  457.         try:
  458.             while self.rawq:
  459.                 c = self.rawq_getchar()
  460.                 if not self.iacseq:
  461.                     if c == theNULL:
  462.                         continue
  463.                     
  464.                     if c == '\x11':
  465.                         continue
  466.                     
  467.                     if c != IAC:
  468.                         buf[self.sb] = buf[self.sb] + c
  469.                         continue
  470.                     else:
  471.                         self.iacseq += c
  472.                 c != IAC
  473.                 if len(self.iacseq) == 1:
  474.                     if c in (DO, DONT, WILL, WONT):
  475.                         self.iacseq += c
  476.                         continue
  477.                     
  478.                     self.iacseq = ''
  479.                     if c == IAC:
  480.                         buf[self.sb] = buf[self.sb] + c
  481.                     elif c == SB:
  482.                         self.sb = 1
  483.                         self.sbdataq = ''
  484.                     elif c == SE:
  485.                         self.sb = 0
  486.                         self.sbdataq = self.sbdataq + buf[1]
  487.                         buf[1] = ''
  488.                     
  489.                     if self.option_callback:
  490.                         self.option_callback(self.sock, c, NOOPT)
  491.                     else:
  492.                         self.msg('IAC %d not recognized' % ord(c))
  493.                 self.option_callback
  494.                 if len(self.iacseq) == 2:
  495.                     cmd = self.iacseq[1]
  496.                     self.iacseq = ''
  497.                     opt = c
  498.                     if cmd in (DO, DONT):
  499.                         if not cmd == DO or 'DO':
  500.                             pass
  501.                         self.msg('IAC %s %d', 'DONT', ord(opt))
  502.                         if self.option_callback:
  503.                             self.option_callback(self.sock, cmd, opt)
  504.                         else:
  505.                             self.sock.sendall(IAC + WONT + opt)
  506.                     elif cmd in (WILL, WONT):
  507.                         if not cmd == WILL or 'WILL':
  508.                             pass
  509.                         self.msg('IAC %s %d', 'WONT', ord(opt))
  510.                         if self.option_callback:
  511.                             self.option_callback(self.sock, cmd, opt)
  512.                         else:
  513.                             self.sock.sendall(IAC + DONT + opt)
  514.                     
  515.                 cmd in (DO, DONT)
  516.         except EOFError:
  517.             self.iacseq = ''
  518.             self.sb = 0
  519.  
  520.         self.cookedq = self.cookedq + buf[0]
  521.         self.sbdataq = self.sbdataq + buf[1]
  522.  
  523.     
  524.     def rawq_getchar(self):
  525.         '''Get next char from raw queue.
  526.  
  527.         Block if no data is immediately available.  Raise EOFError
  528.         when connection is closed.
  529.  
  530.         '''
  531.         if not self.rawq:
  532.             self.fill_rawq()
  533.             if self.eof:
  534.                 raise EOFError
  535.             
  536.         
  537.         c = self.rawq[self.irawq]
  538.         self.irawq = self.irawq + 1
  539.         if self.irawq >= len(self.rawq):
  540.             self.rawq = ''
  541.             self.irawq = 0
  542.         
  543.         return c
  544.  
  545.     
  546.     def fill_rawq(self):
  547.         '''Fill raw queue from exactly one recv() system call.
  548.  
  549.         Block if no data is immediately available.  Set self.eof when
  550.         connection is closed.
  551.  
  552.         '''
  553.         if self.irawq >= len(self.rawq):
  554.             self.rawq = ''
  555.             self.irawq = 0
  556.         
  557.         buf = self.sock.recv(50)
  558.         self.msg('recv %r', buf)
  559.         self.eof = not buf
  560.         self.rawq = self.rawq + buf
  561.  
  562.     
  563.     def sock_avail(self):
  564.         '''Test whether data is available on the socket.'''
  565.         return select.select([
  566.             self], [], [], 0) == ([
  567.             self], [], [])
  568.  
  569.     
  570.     def interact(self):
  571.         '''Interaction function, emulates a very dumb telnet client.'''
  572.         if sys.platform == 'win32':
  573.             self.mt_interact()
  574.             return None
  575.         
  576.         while None:
  577.             (rfd, wfd, xfd) = select.select([
  578.                 self,
  579.                 sys.stdin], [], [])
  580.             if self in rfd:
  581.                 
  582.                 try:
  583.                     text = self.read_eager()
  584.                 except EOFError:
  585.                     print '*** Connection closed by remote host ***'
  586.                     break
  587.  
  588.                 if text:
  589.                     sys.stdout.write(text)
  590.                     sys.stdout.flush()
  591.                 
  592.             
  593.             if sys.stdin in rfd:
  594.                 line = sys.stdin.readline()
  595.                 if not line:
  596.                     break
  597.                 
  598.                 self.write(line)
  599.                 continue
  600.             continue
  601.             return None
  602.  
  603.     
  604.     def mt_interact(self):
  605.         '''Multithreaded version of interact().'''
  606.         import thread
  607.         thread.start_new_thread(self.listener, ())
  608.         while None:
  609.             line = sys.stdin.readline()
  610.             if not line:
  611.                 break
  612.             
  613.             continue
  614.             return None
  615.  
  616.     
  617.     def listener(self):
  618.         '''Helper for mt_interact() -- this executes in the other thread.'''
  619.         while None:
  620.             
  621.             try:
  622.                 data = self.read_eager()
  623.             except EOFError:
  624.                 print '*** Connection closed by remote host ***'
  625.                 return None
  626.  
  627.             if data:
  628.                 sys.stdout.write(data)
  629.                 continue
  630.             sys.stdout.flush()
  631.             continue
  632.             return None
  633.  
  634.     
  635.     def expect(self, list, timeout = None):
  636.         """Read until one from a list of a regular expressions matches.
  637.  
  638.         The first argument is a list of regular expressions, either
  639.         compiled (re.RegexObject instances) or uncompiled (strings).
  640.         The optional second argument is a timeout, in seconds; default
  641.         is no timeout.
  642.  
  643.         Return a tuple of three items: the index in the list of the
  644.         first regular expression that matches; the match object
  645.         returned; and the text read up till and including the match.
  646.  
  647.         If EOF is read and no text was read, raise EOFError.
  648.         Otherwise, when nothing matches, return (-1, None, text) where
  649.         text is the text received so far (may be the empty string if a
  650.         timeout happened).
  651.  
  652.         If a regular expression ends with a greedy match (e.g. '.*')
  653.         or if more than one expression can match the same input, the
  654.         results are undeterministic, and may depend on the I/O timing.
  655.  
  656.         """
  657.         re = None
  658.         list = list[:]
  659.         indices = range(len(list))
  660.         for i in indices:
  661.             if not hasattr(list[i], 'search'):
  662.                 if not re:
  663.                     import re
  664.                 
  665.                 list[i] = re.compile(list[i])
  666.                 continue
  667.         
  668.         if timeout is not None:
  669.             time = time
  670.             import time
  671.             time_start = time()
  672.         
  673.         while None:
  674.             for i in indices:
  675.                 m = list[i].search(self.cookedq)
  676.                 if m:
  677.                     e = m.end()
  678.                     text = self.cookedq[:e]
  679.                     self.cookedq = self.cookedq[e:]
  680.                     return (i, m, text)
  681.                     continue
  682.             
  683.             if self.eof:
  684.                 break
  685.             
  686.             if timeout is not None:
  687.                 elapsed = time() - time_start
  688.                 if elapsed >= timeout:
  689.                     break
  690.                 
  691.                 s_args = ([
  692.                     self.fileno()], [], [], timeout - elapsed)
  693.                 (r, w, x) = select.select(*s_args)
  694.                 if not r:
  695.                     break
  696.                 
  697.             
  698.             self.fill_rawq()
  699.             continue
  700.             text = self.read_very_lazy()
  701.             if not text and self.eof:
  702.                 raise EOFError
  703.             
  704.         return (-1, None, text)
  705.  
  706.  
  707.  
  708. def test():
  709.     '''Test program for telnetlib.
  710.  
  711.     Usage: python telnetlib.py [-d] ... [host [port]]
  712.  
  713.     Default host is localhost; default port is 23.
  714.  
  715.     '''
  716.     debuglevel = 0
  717.     while sys.argv[1:] and sys.argv[1] == '-d':
  718.         debuglevel = debuglevel + 1
  719.         del sys.argv[1]
  720.     host = 'localhost'
  721.     if sys.argv[1:]:
  722.         host = sys.argv[1]
  723.     
  724.     port = 0
  725.     if sys.argv[2:]:
  726.         portstr = sys.argv[2]
  727.         
  728.         try:
  729.             port = int(portstr)
  730.         except ValueError:
  731.             port = socket.getservbyname(portstr, 'tcp')
  732.         except:
  733.             None<EXCEPTION MATCH>ValueError
  734.         
  735.  
  736.     None<EXCEPTION MATCH>ValueError
  737.     tn = Telnet()
  738.     tn.set_debuglevel(debuglevel)
  739.     tn.open(host, port)
  740.     tn.interact()
  741.     tn.close()
  742.  
  743. if __name__ == '__main__':
  744.     test()
  745.  
  746.