python项目之 ftp服务器

景翰音
2023-12-01

python项目之 ftp服务器 源码

参考官方简介自己编写
其中目录是文字会变成乱码,是由于内部采用字符非unicode,此问题待解决。

使用库pyftpdlib

# -*- coding: utf-8 -*-
# edit by liuyunfei 
#2016-01-03

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

import logging
import os
#需修改为本机的IP地址
IP_DEFINE = '192.168.11.106'
PORT_DEFINE = 2121


class MyHandler(FTPHandler):

    def on_connect(self):
        print("%s:%s connected" % (self.remote_ip, self.remote_port))

    def on_disconnect(self):
        # do something when client disconnects
        pass

    def on_login(self, username):
        # do something when user login
        pass

    def on_logout(self, username):
        # do something when user logs out
        pass

    def on_file_sent(self, file):
        # do something when a file has been sent
        pass

    def on_file_received(self, file):
        # do something when a file has been received
        pass

    def on_incomplete_file_sent(self, file):
        # do something when a file is partially sent
        pass

    def on_incomplete_file_received(self, file):
        # remove partially uploaded files
        import os
        os.remove(file)


def main():
    this_dir = os.getcwd()
    logging.basicConfig(filename= this_dir+'/log/logging.log', level=logging.INFO)

    authorizer = DummyAuthorizer()
    #添加用户
    authorizer.add_user('liu', '123456', homedir='/home', perm='elradfmwM')
    #添加匿名用户 只可以浏览
    authorizer.add_anonymous(homedir='/home')

    handler = MyHandler
    handler.authorizer = authorizer
    handler.banner = "welcome from liuyf."
    #定义服务器连接 ip 和port
    server = FTPServer((IP_DEFINE, PORT_DEFINE), handler)
    #定义最大连接数
    server.max_cons = 32
    server.max_cons_per_ip = 10

    server.serve_forever()

if __name__ == "__main__":
    main()

 类似资料: