脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python搭建FTP服务器的方法示例

Python搭建FTP服务器的方法示例

2021-01-06 00:41shu_8708 Python

本篇文章主要介绍了Python搭建FTP服务器的方法示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

Python版本 3.6.2

使用的ftp包:pyftpdlib    pip install pyftpdlib就可以下载安装了

FTP协议下载上传文件在文件过大的情况下会比HTTP更具有优势,更为方便的实现断点上传和进度监控,下面是官方文档中的

基本方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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服务器的方法示例

利用Python从ftp服务器上下载文件

?
1
2
3
4
5
6
7
8
9
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服务器事件回调函数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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://blog.csdn.net/shu_8708/article/details/79000251

延伸 · 阅读

精彩推荐