python实现ftpServer

使用python模拟一个fetServer

 

import os
import socket
import threading
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

_source_root = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
ftp_home = os.path.join(_source_root, "resources\\uploads\\")


def get_ip_by_prefix(prefix):
    _ip = ''
    for ip in socket.gethostbyname_ex(socket.gethostname())[2]:
        if ip.startswith(prefix):
            _ip = ip
    return _ip


class FtpServer:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super(FtpServer, cls).__new__(cls, *args, **kwargs)
            cls._instance.init_server()
        return cls._instance

    def init_server(self):
        auth = DummyAuthorizer()
        auth.add_user("123", "123", homedir=ftp_home, perm="elradfmw")
        auth.add_anonymous(homedir=ftp_home, perm="elradfmw")

        handler = FTPHandler
        handler.authorizer = auth

        # 使用本机小网ip作为ftpServer
        address = (get_ip_by_prefix("192."), 21)
        self.server = FTPServer(address, handler)

    def start(self):
        self.server.serve_forever()


def start_ftp_server():
    server = FtpServer()
    server.start()


def ftp_server_runner():
    t = threading.Thread(target=start_ftp_server)
    t.daemon = True
    t.start()
    try:
        while True:
            pass
    except KeyboardInterrupt:
        print("shutting Down")


if __name__ == "__main__":
    ftp_server_runner()

 

posted @ 2024-07-25 19:13  _titleInfo  阅读(70)  评论(0编辑  收藏  举报
//雪花飘落效果