Wednesday, November 30, 2011

I've recently run into the need to create a simple StatefulTelnetProtocol Telnet server. But, most of the examples have lots of extra cruft in the way. So, here's what I came up with by removing some extras from a post I found online: --> Note: I don't know the difference (yet) between doing a self.sendLine() and a self.transport.write() call. Feel free to comment if you know the distinction.
from twisted.internet.protocol import ServerFactory, Protocol
from twisted.conch.telnet import StatefulTelnetProtocol
from twisted.internet import reactor
from time import sleep

class MyProtocol(StatefulTelnetProtocol):
    
    def connectionMade(self):
        print "DEBUG: connectionMade called"
        self.sendLine("***************************************\r\n")
        self.sendLine("Welcome to the Simplified Telnet Server\r\n")
        self.sendLine("***************************************\r\n")
        sleep(2)
        self.transport.write("Can also send a line this way.\r\n")
        self.clearLineBuffer()
     
    def lineReceived(self, line):
        print "DEBUG: lineReceived called with %s" % line.strip()
        if line.strip() != "exit":
            self.sendLine("***************************************\r\n")
            #self.transport.write("TRANSPORT_WRITE: GOT LINE='%s'\n" % (str(line.strip())))
        else:
            print "telnet killed in line: %s" % str(line.strip())
            self.sendLine("TelnetShell killed. Bye Bye ...")
            self.transport.loseConnection()
            self.clearLineBuffer()
     
    def connectionLost(self, reason):
        print "DEBUG: connectionLost called with: %s" % str(reason)
     
def CreateMyFactory():
    factory = ServerFactory()
    factory.protocol = MyProtocol
    return factory
 
if __name__ == "__main__":
    MaFactory = CreateMyFactory()
    reactor.listenTCP(8023, MaFactory)
    reactor.run()