[Twisted-Python] Telnet negotiation with Twisted

exarkun at twistedmatrix.com exarkun at twistedmatrix.com
Sat Dec 3 09:48:56 EST 2011


On 02:22 pm, twisted at patrickmylund.com wrote:
>Hi Lee,
>
>Here is a complete example that works with Twisted 11.0. LINEMODE
>itself is enabled at connect, but it has different modes that
>determine what is sent when by the client. (See section 2.2 of
>http://www.faqs.org/rfcs/rfc1184.html)

You can manage this without a TelnetTransport subclass:

#!/usr/bin/env python
from twisted.internet.protocol import Factory
from twisted.conch.telnet import (
    TelnetProtocol, StatefulTelnetProtocol, TelnetTransport)
from twisted.conch.telnet import DO, DONT, WILL, WONT

LINEMODE = chr(34)
LINEMODE_EDIT = chr(1) + chr(1)
LINEMODE_TRAPSIG = chr(1) + chr(2)
LINEMODE_MODEACK = chr(1) + chr(4)
LINEMODE_SOFTTAB = chr(1) + chr(8)
LINEMODE_LITECHO = chr(1) + chr(16)

class LineModeProtocol(TelnetProtocol):

    def connectionMade(self):
        print("Connection made!")
        self.lines = True
        # Ask client to begin sub-negotation of linemode
        self.transport.do(LINEMODE)

    def connectionLost(self, reason):
        print("Connection lost!")

    def enableRemote(self, option):
        if option == LINEMODE:
            # The normal (buffered) mode
            self.transport.requestNegotiation(
                LINEMODE, LINEMODE_EDIT)
            return True
        return False

    def dataReceived(self, data):
        if self.lines:
            line = data.rstrip()
            print("data received (normal): " + line)
            if line == "gounbuffered":
                # Only trap signals locally
                self.transport.requestNegotiation(
                    LINEMODE, LINEMODE_TRAPSIG)                self.lines 
= False
        else:
            # manually buffer data here
            print("data received (linemode): " + data)
            if data == "n":
                # Change to edit mode
                self.transport.requestNegotiation(
                    LINEMODE, LINEMODE_EDIT)
                self.lines = True

class LineModeFactory(Factory):

    def buildProtocol(self, addr):
        return TelnetTransport(LineModeProtocol)

if __name__ == '__main__':
    from twisted.internet import reactor

    port = 2222
    factory = LineModeFactory()

    reactor.listenTCP(port, factory)
    reactor.run()

Jean-Paul



More information about the Twisted-Python mailing list