Question

I need to create twisted SSH server that accepts several commands. But the main feature is that server should manage connection. To be more specific, it needs to close open connection if it lasts for more than 10 minutes (for example). Or it should not accept new connection if there are already 10 open connections.

In fact I still cannot fully understand how all these realms, avatars, protocol and portals, etc. interact with each other. And I feel strong lack of documentation. There are several examples, but without any comments about what exactly is happening on each step.

Anyway, trying and failing I was able to add execution of needed commands to twisted simple ssh server example. But I'm totally loss on how I can reject new connection or close existing or add some time flag for new connection that can be used to close connection when it reaches time limit.

Any help would be appreciated. Please be kind to me, I never worked with Twisted and actually I'm newby in python :)

Thank you.

p.s. I'm sorry for possible mistakes, English is not my native.

No correct solution

OTHER TIPS

So, the main problem is to limit the number of connections. This is really depends on the protocol you would like to use. Let's assume, you use LineOnlyReceiver as a base protocol (other inheritors of Prototol will behave the same way, but, for example, AMP will be a bit different case):

from twisted.internet.protocol import ServerFactory
from twisted.protocols.basic import LineOnlyReceiver


class NoConnectionSlots(Exception):
    message = "Sorry, bro. There are no free slots for you. Try again later."


class ExampleProtocol(LineOnlyReceiver):

    def connectionMade(self):
        try:
            self.factory.client_connected(self)
        except NoConnectionSlots as e:
            self.sendLine("{:}\\n".format(unicode(e)))
            self.transport.loseConnection()

    def connectionLost(self, reason):
        self.factory.client_left(self)


class ExampleServerFactory(ServerFactory):

    protocol = ExampleProtocol
    max_connections = 10

    def __init__(self):
        self._connections = []

    def client_connected(self, connection):
        if len(self._connections) < self.max_connections:
            raise NoConnectionSlots()
        self._connections.append(connection)

    def client_left(self, connection):
        try:
            self._connections.remove(connection)
        except ValueError as e:
            pass  # place for logging
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top