本篇文章主要介绍了 Python 搭建 FTP 服务器的方法示例, 小编觉得挺不错的, 现在分享给大家, 也给大家做个参考一起跟随小编过来看看吧
Python 版本 3.6.2
使用的 ftp 包: pyftpdlib pip install pyftpdlib 就可以下载安装了
FTP 协议下载上传文件在文件过大的情况下会比 HTTP 更具有优势, 更为方便的实现断点上传和进度监控, 下面是官方文档中的
基本方法
- import os
- from pyftpdlib.authorizers import DummyAuthorizer
- from pyftpdlib.handlers import FTPHandler
- from pyftpdlib.servers import FTPServer
- def main():
- # 实例化用户授权管理
- authorizer = DummyAuthorizer()
- authorizer.add_user('user', '12345', 'path', perm='elradfmwMT')# 添加用户 参数: username,password, 允许的路径, 权限
- authorizer.add_anonymous(os.getcwd())# 这里是允许匿名用户, 如果不允许删掉此行即可
- # 实例化 FTPHandler
- handler = FTPHandler
- handler.authorizer = authorizer
- # 设定一个客户端链接时的标语
- handler.banner = "pyftpdlib based ftpd ready."
- #handler.masquerade_address = '151.25.42.11'# 指定伪装 ip 地址
- #handler.passive_ports = range(60000, 65535)# 指定允许的端口范围
- address = (ipaddr, 21)#FTP 一般使用 21,20 端口
- server = FTPServer(address, handler)#FTP 服务器实例
- # set a limit for connections
- server.max_cons = 256
- server.max_cons_per_ip = 5
- # 开启服务器
- server.serve_forever()
- if __name__ == '__main__':
- main()
开启 ftp 服务器后要确定防火墙开启了 21,20 端口, 并且在客户端的浏览器中设置 internet 选项高级选项卡中的被动 ftp 的勾去掉之后才能登陆到 ftp 服务器
从 Windows 登录到服务器:
利用 Python 从 ftp 服务器上下载文件
- from ftplib import FTP
- ftp=FTP()
- ftp.connect('localhost',21)#localhost 改成服务器 ip 地址
- ftp.login(user='user',passwd='12345')
- file=open('f://ftpdownload/test.txt','wb')
- ftp.retrbinary("RETR test.txt",file.write,1024)# 从服务器上下载文件 1024 字节一个块
- ftp.set_debuglevel(0)
- ftp.close()
FTP 服务器事件回调函数:
- 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)
来源: http://www.phperz.com/article/18/0222/362977.html