cinap_lenrekadd hg and python4bb9e2215 years agoHistory
669 lines · 21.6 KB · Python
RawDownload
r"""TELNET client class. Based on RFC 854: TELNET Protocol Specification, by J. Postel andJ. Reynolds Example: >>> from telnetlib import Telnet>>> tn = Telnet('www.python.org', 79)   # connect to finger port>>> tn.write('guido\r\n')>>> print tn.read_all()Login       Name               TTY         Idle    When    Whereguido    Guido van Rossum      pts/2        <Dec  2 11:10> snag.cnri.reston.. >>> Note that read_all() won't read until eof -- it just reads some data-- but it guarantees to read at least one byte unless EOF is hit. It is possible to pass a Telnet object to select.select() in order towait until more data is available.  Note that in this case,read_eager() may return '' even if there was data on the socket,because the protocol negotiation may have eaten the data.  This is whyEOFError is needed in some cases to distinguish between "no data" and"connection closed" (since the socket also appears ready for readingwhen it is closed). To do:- option negotiation- timeout should be intrinsic to the connection object instead of an  option on one of the read calls only """  # Imported modulesimport sysimport socketimport select __all__ = ["Telnet"] # Tunable parametersDEBUGLEVEL = 0 # Telnet protocol defaultsTELNET_PORT = 23 # Telnet protocol characters (don't change)IAC  = chr(255) # "Interpret As Command"DONT = chr(254)DO   = chr(253)WONT = chr(252)WILL = chr(251)theNULL = chr(0) SE  = chr(240)  # Subnegotiation EndNOP = chr(241)  # No OperationDM  = chr(242)  # Data MarkBRK = chr(243)  # BreakIP  = chr(244)  # Interrupt processAO  = chr(245)  # Abort outputAYT = chr(246)  # Are You ThereEC  = chr(247)  # Erase CharacterEL  = chr(248)  # Erase LineGA  = chr(249)  # Go AheadSB =  chr(250)  # Subnegotiation Begin  # Telnet protocol options code (don't change)# These ones all come from arpa/telnet.hBINARY = chr(0) # 8-bit data pathECHO = chr(1) # echoRCP = chr(2) # prepare to reconnectSGA = chr(3) # suppress go aheadNAMS = chr(4) # approximate message sizeSTATUS = chr(5) # give statusTM = chr(6) # timing markRCTE = chr(7) # remote controlled transmission and echoNAOL = chr(8) # negotiate about output line widthNAOP = chr(9) # negotiate about output page sizeNAOCRD = chr(10) # negotiate about CR dispositionNAOHTS = chr(11) # negotiate about horizontal tabstopsNAOHTD = chr(12) # negotiate about horizontal tab dispositionNAOFFD = chr(13) # negotiate about formfeed dispositionNAOVTS = chr(14) # negotiate about vertical tab stopsNAOVTD = chr(15) # negotiate about vertical tab dispositionNAOLFD = chr(16) # negotiate about output LF dispositionXASCII = chr(17) # extended ascii character setLOGOUT = chr(18) # force logoutBM = chr(19) # byte macroDET = chr(20) # data entry terminalSUPDUP = chr(21) # supdup protocolSUPDUPOUTPUT = chr(22) # supdup outputSNDLOC = chr(23) # send locationTTYPE = chr(24) # terminal typeEOR = chr(25) # end or recordTUID = chr(26) # TACACS user identificationOUTMRK = chr(27) # output markingTTYLOC = chr(28) # terminal location numberVT3270REGIME = chr(29) # 3270 regimeX3PAD = chr(30) # X.3 PADNAWS = chr(31) # window sizeTSPEED = chr(32) # terminal speedLFLOW = chr(33) # remote flow controlLINEMODE = chr(34) # Linemode optionXDISPLOC = chr(35) # X Display LocationOLD_ENVIRON = chr(36) # Old - Environment variablesAUTHENTICATION = chr(37) # AuthenticateENCRYPT = chr(38) # Encryption optionNEW_ENVIRON = chr(39) # New - Environment variables# the following ones come from# http://www.iana.org/assignments/telnet-options# Unfortunately, that document does not assign identifiers# to all of them, so we are making them upTN3270E = chr(40) # TN3270EXAUTH = chr(41) # XAUTHCHARSET = chr(42) # CHARSETRSP = chr(43) # Telnet Remote Serial PortCOM_PORT_OPTION = chr(44) # Com Port Control OptionSUPPRESS_LOCAL_ECHO = chr(45) # Telnet Suppress Local EchoTLS = chr(46) # Telnet Start TLSKERMIT = chr(47) # KERMITSEND_URL = chr(48) # SEND-URLFORWARD_X = chr(49) # FORWARD_XPRAGMA_LOGON = chr(138) # TELOPT PRAGMA LOGONSSPI_LOGON = chr(139) # TELOPT SSPI LOGONPRAGMA_HEARTBEAT = chr(140) # TELOPT PRAGMA HEARTBEATEXOPL = chr(255) # Extended-Options-ListNOOPT = chr(0) class Telnet:     """Telnet interface class.     An instance of this class represents a connection to a telnet    server.  The instance is initially not connected; the open()    method must be used to establish a connection.  Alternatively, the    host name and optional port number can be passed to the    constructor, too.     Don't try to reopen an already connected instance.     This class has many read_*() methods.  Note that some of them    raise EOFError when the end of the connection is read, because    they can return an empty string for other reasons.  See the    individual doc strings.     read_until(expected, [timeout])        Read until the expected string has been seen, or a timeout is        hit (default is no timeout); may block.     read_all()        Read all data until EOF; may block.     read_some()        Read at least one byte or EOF; may block.     read_very_eager()        Read all data available already queued or on the socket,        without blocking.     read_eager()        Read either data already queued or some data available on the        socket, without blocking.     read_lazy()        Read all data in the raw queue (processing it first), without        doing any socket I/O.     read_very_lazy()        Reads all data in the cooked queue, without doing any socket        I/O.     read_sb_data()        Reads available data between SB ... SE sequence. Don't block.     set_option_negotiation_callback(callback)        Each time a telnet option is read on the input flow, this callback        (if set) is called with the following parameters :        callback(telnet socket, command, option)            option will be chr(0) when there is no option.        No other action is done afterwards by telnetlib.     """     def __init__(self, host=None, port=0):        """Constructor.         When called without arguments, create an unconnected instance.        With a hostname argument, it connects the instance; a port        number is optional.         """        self.debuglevel = DEBUGLEVEL        self.host = host        self.port = port        self.sock = None        self.rawq = ''        self.irawq = 0        self.cookedq = ''        self.eof = 0        self.iacseq = '' # Buffer for IAC sequence.        self.sb = 0 # flag for SB and SE sequence.        self.sbdataq = ''        self.option_callback = None        if host is not None:            self.open(host, port)     def open(self, host, port=0):        """Connect to a host.         The optional second argument is the port number, which        defaults to the standard telnet port (23).         Don't try to reopen an already connected instance.         """        self.eof = 0        if not port:            port = TELNET_PORT        self.host = host        self.port = port        msg = "getaddrinfo returns an empty list"        for res in socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM):            af, socktype, proto, canonname, sa = res            try:                self.sock = socket.socket(af, socktype, proto)                self.sock.connect(sa)            except socket.error, msg:                if self.sock:                    self.sock.close()                self.sock = None                continue            break        if not self.sock:            raise socket.error, msg     def __del__(self):        """Destructor -- close the connection."""        self.close()     def msg(self, msg, *args):        """Print a debug message, when the debug level is > 0.         If extra arguments are present, they are substituted in the        message using the standard string formatting operator.         """        if self.debuglevel > 0:            print 'Telnet(%s,%d):' % (self.host, self.port),            if args:                print msg % args            else:                print msg     def set_debuglevel(self, debuglevel):        """Set the debug level.         The higher it is, the more debug output you get (on sys.stdout).         """        self.debuglevel = debuglevel     def close(self):        """Close the connection."""        if self.sock:            self.sock.close()        self.sock = 0        self.eof = 1        self.iacseq = ''        self.sb = 0     def get_socket(self):        """Return the socket object used internally."""        return self.sock     def fileno(self):        """Return the fileno() of the socket object used internally."""        return self.sock.fileno()     def write(self, buffer):        """Write a string to the socket, doubling any IAC characters.         Can block if the connection is blocked.  May raise        socket.error if the connection is closed.         """        if IAC in buffer:            buffer = buffer.replace(IAC, IAC+IAC)        self.msg("send %r", buffer)        self.sock.sendall(buffer)     def read_until(self, match, timeout=None):        """Read until a given string is encountered or until timeout.         When no match is found, return whatever is available instead,        possibly the empty string.  Raise EOFError if the connection        is closed and no cooked data is available.         """        n = len(match)        self.process_rawq()        i = self.cookedq.find(match)        if i >= 0:            i = i+n            buf = self.cookedq[:i]            self.cookedq = self.cookedq[i:]            return buf        s_reply = ([self], [], [])        s_args = s_reply        if timeout is not None:            s_args = s_args + (timeout,)            from time import time            time_start = time()        while not self.eof and select.select(*s_args) == s_reply:            i = max(0, len(self.cookedq)-n)            self.fill_rawq()            self.process_rawq()            i = self.cookedq.find(match, i)            if i >= 0:                i = i+n                buf = self.cookedq[:i]                self.cookedq = self.cookedq[i:]                return buf            if timeout is not None:                elapsed = time() - time_start                if elapsed >= timeout:                    break                s_args = s_reply + (timeout-elapsed,)        return self.read_very_lazy()     def read_all(self):        """Read all data until EOF; block until connection closed."""        self.process_rawq()        while not self.eof:            self.fill_rawq()            self.process_rawq()        buf = self.cookedq        self.cookedq = ''        return buf     def read_some(self):        """Read at least one byte of cooked data unless EOF is hit.         Return '' if EOF is hit.  Block if no data is immediately        available.         """        self.process_rawq()        while not self.cookedq and not self.eof:            self.fill_rawq()            self.process_rawq()        buf = self.cookedq        self.cookedq = ''        return buf     def read_very_eager(self):        """Read everything that's possible without blocking in I/O (eager).         Raise EOFError if connection closed and no cooked data        available.  Return '' if no cooked data available otherwise.        Don't block unless in the midst of an IAC sequence.         """        self.process_rawq()        while not self.eof and self.sock_avail():            self.fill_rawq()            self.process_rawq()        return self.read_very_lazy()     def read_eager(self):        """Read readily available data.         Raise EOFError if connection closed and no cooked data        available.  Return '' if no cooked data available otherwise.        Don't block unless in the midst of an IAC sequence.         """        self.process_rawq()        while not self.cookedq and not self.eof and self.sock_avail():            self.fill_rawq()            self.process_rawq()        return self.read_very_lazy()     def read_lazy(self):        """Process and return data that's already in the queues (lazy).         Raise EOFError if connection closed and no data available.        Return '' if no cooked data available otherwise.  Don't block        unless in the midst of an IAC sequence.         """        self.process_rawq()        return self.read_very_lazy()     def read_very_lazy(self):        """Return any data available in the cooked queue (very lazy).         Raise EOFError if connection closed and no data available.        Return '' if no cooked data available otherwise.  Don't block.         """        buf = self.cookedq        self.cookedq = ''        if not buf and self.eof and not self.rawq:            raise EOFError, 'telnet connection closed'        return buf     def read_sb_data(self):        """Return any data available in the SB ... SE queue.         Return '' if no SB ... SE available. Should only be called        after seeing a SB or SE command. When a new SB command is        found, old unread SB data will be discarded. Don't block.         """        buf = self.sbdataq        self.sbdataq = ''        return buf     def set_option_negotiation_callback(self, callback):        """Provide a callback function called after each receipt of a telnet option."""        self.option_callback = callback     def process_rawq(self):        """Transfer from raw queue to cooked queue.         Set self.eof when connection is closed.  Don't block unless in        the midst of an IAC sequence.         """        buf = ['', '']        try:            while self.rawq:                c = self.rawq_getchar()                if not self.iacseq:                    if c == theNULL:                        continue                    if c == "\021":                        continue                    if c != IAC:                        buf[self.sb] = buf[self.sb] + c                        continue                    else:                        self.iacseq += c                elif len(self.iacseq) == 1:                    # 'IAC: IAC CMD [OPTION only for WILL/WONT/DO/DONT]'                    if c in (DO, DONT, WILL, WONT):                        self.iacseq += c                        continue                     self.iacseq = ''                    if c == IAC:                        buf[self.sb] = buf[self.sb] + c                    else:                        if c == SB: # SB ... SE start.                            self.sb = 1                            self.sbdataq = ''                        elif c == SE:                            self.sb = 0                            self.sbdataq = self.sbdataq + buf[1]                            buf[1] = ''                        if self.option_callback:                            # Callback is supposed to look into                            # the sbdataq                            self.option_callback(self.sock, c, NOOPT)                        else:                            # We can't offer automatic processing of                            # suboptions. Alas, we should not get any                            # unless we did a WILL/DO before.                            self.msg('IAC %d not recognized' % ord(c))                elif len(self.iacseq) == 2:                    cmd = self.iacseq[1]                    self.iacseq = ''                    opt = c                    if cmd in (DO, DONT):                        self.msg('IAC %s %d',                            cmd == DO and 'DO' or 'DONT', ord(opt))                        if self.option_callback:                            self.option_callback(self.sock, cmd, opt)                        else:                            self.sock.sendall(IAC + WONT + opt)                    elif cmd in (WILL, WONT):                        self.msg('IAC %s %d',                            cmd == WILL and 'WILL' or 'WONT', ord(opt))                        if self.option_callback:                            self.option_callback(self.sock, cmd, opt)                        else:                            self.sock.sendall(IAC + DONT + opt)        except EOFError: # raised by self.rawq_getchar()            self.iacseq = '' # Reset on EOF            self.sb = 0            pass        self.cookedq = self.cookedq + buf[0]        self.sbdataq = self.sbdataq + buf[1]     def rawq_getchar(self):        """Get next char from raw queue. 

Lines 1–500 of 669.