Python Twisted-如何记录服务器接收的FTP命令

Python Twisted-如何记录服务器接收的FTP命令,python,ftp,twisted,Python,Ftp,Twisted,我使用twisted作为FTP服务器: from twisted.protocols.ftp import FTPFactory, FTPRealm from twisted.cred.portal import Portal from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB from twisted.internet import reactor p = Portal(FTPRealm('./'),

我使用twisted作为FTP服务器:

from twisted.protocols.ftp import FTPFactory, FTPRealm
from twisted.cred.portal import Portal
from twisted.cred.checkers import AllowAnonymousAccess, FilePasswordDB
from twisted.internet import reactor

p = Portal(FTPRealm('./'),
           [AllowAnonymousAccess(), FilePasswordDB("pass.dat")])

f = FTPFactory(p)

reactor.listenTCP(21, f)
reactor.run()

如何记录从客户端接收到的每个FTP命令?

FTPRealm
创建
FTPAnonymousShell
FTPShell
实例(化身),以协调对文件系统的访问

这些类都实现了
IFTPShell
。一种解决方案是为
FTPRealm
创建一个包装器,将日志包装器应用于它创建的化身

from twisted.python.components import proxyForInterface

class WrappingRealm(proxyForInterface(IRealm)):
    wrap = staticmethod(logging_wrapper)

    def requestAvatar(self, *a, **kw):
        d = maybeDeferred(
            super(WrappingRealm, self).requestAvatar,
            *a, **kw
        )
        def got_avatar((iface, avatar, logout)):
            return (iface, self.wrap(avatar), logout)
       d.addCallback(got_avatar)
       return d
并实现
logging\u wrapper
类似于:

class _LoggingFTPShell(proxyForInterface(IFTPShell)):
    def makeDirectory(self, path):
        log(avatar=self.avatar, operation="makeDirectory", path=path)
        return super(_LoggingFTPShell, self).makeDirectory(path)

    # The same for the rest of the methods of IFTPShell
    # ...

def logging_wrapper(avatar):
    return _LoggingFTPShell(avatar)
这有点乏味,因为必须为接口上的每个方法添加日志记录。然而,由于Twisted的FTP协议实现在本机上不提供执行所需日志记录的工具,因此很难避免这种情况。通过一些元编程,您可以节省一些输入(但要付出一些复杂的代价)

另一种方法是为Twisted添加一个补丁,以添加您感兴趣的日志记录。

此示例是否有帮助?