Telnetlib to twisted

Jean-Paul Calderone exarkun at divmod.com
Fri Oct 27 14:31:20 EDT 2006


On Fri, 27 Oct 2006 16:40:44 +0100, Matthew Warren <matthew.warren at digica.com> wrote:
>Hallo,
>
>>>> import telnetlib
>>>> l=telnetlib.Telnet('dbprod')
>>>> l.interact()
>telnet (dbprod)
>
>Login:
>
>
>Could anyone show how the above would be written using the twisted
>framework? All I'm after is a more 'intelligent' interactive telnet
>session (handles 'vi' etc..) rather than the full capabilities of the
>twisted framework.
>

Basically you want to hook up a telnet connection to stdio.  You can find
a couple examples of using stdio in a Twisted application here:

http://twistedmatrix.com/projects/core/documentation/examples/stdiodemo.py
http://twistedmatrix.com/projects/core/documentation/examples/stdin.py

Then you need a telnet connection to send the bytes you read from stdin to
and from which to receive bytes to write to stdout.

I don't think there are any good examples of using telnet as a client, but
it's pretty straightforward.  Something like this, for example, will make
a telnet connection and then write all the non-telnet negotiation data to
stdout:

  from twisted.internet.protocol import ClientCreator, reactor
  from twisted.conch.telnet import Telnet
  
  class PrintingTelnet(Telnet):
      def applicationDataReceived(self, bytes):
          print bytes

  def main():
      cc = ClientCreator(reactor, PrintingTelnet)
      d = cc.connectTCP(host, port)
      def connected(proto):
          print 'Connected'
      reactor.run()

  if __name__ == '__main__':
      main()

The part where a lot of people get stuck is hooking up the stdio protocol
to the network protocol.  For this, you just need to make sure each
instance has a reference to the other.  You can then call methods on the
stdio protocol from the telnet protocol when bytes are received, and vice
versa.

You may need to add in a layer to handle terminal control sequences, since
those pass through telnet and will get through to your application.  On the
other hand, if all you do is write them to stdout, your actual terminal
should handle them.  You'll only need an extra layer if you want to do extra
interpretation.

Hope this helps,

Jean-Paul



More information about the Python-list mailing list