2

我需要创建接受多个命令的扭曲 SSH 服务器。但主要特点是服务器应该管理连接。更具体地说,如果持续时间超过 10 分钟(例如),则需要关闭打开的连接。或者如果已经有 10 个打开的连接,它不应该接受新连接。

事实上,我仍然无法完全理解所有这些领域、化身、协议和门户等是如何相互作用的。而且我觉得非常缺乏文档。有几个例子,但没有任何关于每一步究竟发生了什么的评论。

无论如何,尝试和失败我能够将所需命令的执行添加到扭曲的简单 ssh 服务器示例。但是我完全不知道如何拒绝新连接或关闭现有连接或为新连接添加一些时间标志,可用于在达到时间限制时关闭连接。

任何帮助,将不胜感激。请善待我,我从未与 Twisted 合作过,实际上我是 python 的新手 :)

谢谢你。

ps 对于可能的错误,我很抱歉,英语不是我的母语。

4

1 回答 1

0

因此,主要问题是限制连接数。这实际上取决于您要使用的协议。假设,您将LineOnlyReceiver其用作基本协议(其他继承者的Prototol行为方式相同,但例如,AMP情况会有所不同):

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
于 2014-07-18T09:04:55.170 回答