如何管理扭曲的SSH服务器连接

2024-05-12 15:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

事实上,我仍然无法完全理解所有这些领域、化身、协议和门户等是如何相互作用的。我觉得缺乏文件。这里有几个例子,但没有对每一步到底发生了什么评论。在

不管怎样,不管怎样,我都能够将所需命令的执行添加到twisted simple ssh server example。但我完全不知道如何才能拒绝新连接或关闭现有连接,或为新连接添加一些时间标记,以便在达到时间限制时关闭连接。在

任何帮助都将不胜感激。请善待我,我从来没有和Twisted合作过,实际上我是python新手:)

谢谢。在

另外,我为可能的错误道歉,英语不是我的母语。在


Tags: 文件命令服务器协议门户时间评论twisted
1条回答
网友
1楼 · 发布于 2024-05-12 15:25:49

所以,主要的问题是限制连接的数量。这实际上取决于你想使用的协议。假设您使用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

相关问题 更多 >