HowTo Telnet by twisted.conch.telnet?
I understand, that Telnet from twisted.protocols.telnet is deprecated. However, I can't see how the newer Telnet from twisted.conch.telnet will replace it. I wrote a very simple piece of telnet authentication code, that goes like this:
from twisted.protocols.telnet import Telnet
class MyProtocol(Telnet):
def welcomeMessage(self):
return "Hi, Welcome to my telnet server"
def loginPrompt(self):
return "Who are you ?"
def checkUserAndPass (self,u,p):
# some stuff here
def telnet_Command(self, cmd):
self.transport.write("you typed " + cmd)
It works fine, but the newer Telnet class has开发者_运维百科 none of these Standard methods. I checked out AuthenticatingTelnetProtocol, too, but most of it is not documented. Can anybody point me to an example, that does (more or less) the same as the code above or rewrite it ? Thanks in advance
A major difference between twisted.protocols.telnet
and twisted.conch.telnet
is that the former implements part of the Telnet protocol (RFC 854) and adds some "convenience" functionality which applies for standard username/password login-style sessions, whereas the latter implements all of the Telnet protocol and leaves the "convenience" stuff up to the application developer.
Fortunately this "convenience" functionality isn't hard to implement yourself. It's basically two things: parsing lines from the client and calling a different method depending on what stage (or "state") the connection is in. LineReceiver
will do the former, and the latter is simple. So, for example:
from twisted.protocols.basic import LineReceiver
from twisted.conch.telnet import TelnetProtocol
class SimpleTelnetSession(LineReceiver, TelnetProtocol):
def connectionMade(self):
self.transport.write('Username: ')
self.state = 'USERNAME'
def lineReceived(self, line):
getattr(self, 'telnet_' + self.state)(line)
def telnet_USERNAME(self, line):
self.username = line
self.transport.write('Password: ')
self.state = 'PASSWORD'
...
This is more or less what AuthenticatingTelnetProtocol
is implementing, too.
精彩评论