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("Welcome to the Simplified Telnet Server\r\n")
        self.transport.write("Can also send a line this way.\r\n")
    def lineReceived(self, line):
        print "DEBUG: lineReceived called with %s" % line.strip()
        if line.strip() != "exit":
            #self.transport.write("TRANSPORT_WRITE: GOT LINE='%s'\n" % (str(line.strip())))
            print "telnet killed in line: %s" % str(line.strip())
            self.sendLine("TelnetShell killed. Bye Bye ...")
    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)
Post a Comment