How can I do SSH port forwarding from within Python Twisted?

It would be awesome if there were improved documentation in Twisted for doing neat things with Conch (after all, how many other programmable SSH libraries are there?). Until that happy day comes, reading the implementation of the conch command line tool can be a big help.

Here we can see where port forwarding options from the command line are turned into some action over the SSH connection:

https://github.com/twisted/twisted/blob/4ffbe9f6851dbe7e9172f55905f264ecf50da3a6/src/twisted/conch/scripts/conch.py#L226-L238

I think you're asking about a local forwarding rule, so the localForwards loop is doing roughly what you want to do.


Implementing a tunneling Twisted SSH client that does local port forwarding can be surprisingly simple.

Just create a basic Twisted Conch SSH client, and implement the port forwarding part in the serviceStarted method of the SSH connection class of your client:

from twisted.conch.ssh import forwarding

LOCALPORT = 8888
REMOTEHOST = "127.0.0.1"
REMOTEPORT = 9999

class Connection(connection.SSHConnection):

    def serviceStarted(self):
       Channel = forwarding.SSHListenClientForwardingChannel
       Factory = forwarding.SSHListenForwardingFactory
       factory = Factory(self, (REMOTEHOST, REMOTEPORT), Channel)
       s = reactor.listenTCP(LOCALPORT, factory)

That's all there's to it (REMOTEHOST is set to point to ssh server itself since that's what you said you're connecting to).