pyftpdlib 实现FTP服务器

pyftpdlib 默认是被动模式,如果没有设置数据传输默认端口范围,则默认为60000-65535。这就需要服务端开放命令端口21和数据范围端口

FTP传输协议

  • 双向传输:需要建立两个TCP连接,一个用于传输命令,一个用于传输数据
  • 21端口用于传输命令端口
  • 主动模式:在客户端连接21端口时发送一个数据传输端口,以便可以让服务端使用20端口来连接。要求客户端开放防火墙
  • 被动模式:要求服务端开启数据传输端口

pyftpdlib 基础FTP服务

import os

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

def main():
    # Instantiate a dummy authorizer for managing 'virtual' users
    authorizer = DummyAuthorizer()

    # Define a new user having full r/w permissions and a read-only
    # anonymous user
    authorizer.add_user('user', '12345', '.', perm='elradfmwMT')
    authorizer.add_anonymous(os.getcwd())

    # Instantiate FTP handler class
    handler = FTPHandler
    handler.authorizer = authorizer

    # Define a customized banner (string returned when client connects)
    handler.banner = "pyftpdlib based ftpd ready."

    # Specify a masquerade address and the range of ports to use for
    # passive connections.  Decomment in case you're behind a NAT.
    #handler.masquerade_address = '151.25.42.11'
    #handler.passive_ports = range(60000, 65535)

    # Instantiate FTP server class and listen on 0.0.0.0:2121
    address = ('', 2121)
    server = FTPServer(address, handler)

    # set a limit for connections
    server.max_cons = 256
    server.max_cons_per_ip = 5

    # start ftp server
    server.serve_forever()

if __name__ == '__main__':
    main()


来自为知笔记(Wiz)


posted on 2024-03-26 22:21  白衣风云  阅读(102)  评论(0编辑  收藏  举报

导航