Python版本 3.6.2
使用的ftp包:pyftpdlib pip install pyftpdlib就可以下载安装了
FTP协议下载上传文件在文件过大的情况下会比HTTP更具有优势,更为方便的实现断点上传和进度监控,下面是官方文档中的基本方法
代码语言:javascript复制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服务器上下载文件
代码语言:javascript复制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服务器事件回调函数:
代码语言:javascript复制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)