來源:shu_8708 發(fā)布時間:2018-11-03 15:44:54 閱讀量:1186
使用的ftp包:pyftpdlib pip install pyftpdlib就可以下載安裝了
FTP協(xié)議下載上傳文件在文件過大的情況下會比HTTP更具有優(yōu)勢,更為方便的實現(xiàn)斷點上傳和進度監(jiān)控,下面是官方文檔中的基本方法
import os
from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer
def main():
# 實例化用戶授權(quán)管理
authorizer = DummyAuthorizer()
authorizer.add_user('user', '12345', 'path', perm='elradfmwMT')#添加用戶 參數(shù):username,password,允許的路徑,權(quán)限
authorizer.add_anonymous(os.getcwd())#這里是允許匿名用戶,如果不允許刪掉此行即可
# 實例化FTPHandler
handler = FTPHandler
handler.authorizer = authorizer
# 設(shè)定一個客戶端鏈接時的標(biāo)語
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服務(wù)器實例
# set a limit for connections
server.max_cons = 256
server.max_cons_per_ip = 5
# 開啟服務(wù)器
server.serve_forever()
if __name__ == '__main__':
main()
開啟ftp服務(wù)器后要確定防火墻開啟了21,20端口,并且在客戶端的瀏覽器中設(shè)置internet選項高級選項卡中的被動ftp的勾去掉之后才能登陸到ftp服務(wù)器
從Windows登錄到服務(wù)器:
利用Python從ftp服務(wù)器上下載文件
from ftplib import FTP
ftp=FTP()
ftp.connect('localhost',21)#localhost改成服務(wù)器ip地址
ftp.login(user='user',passwd='12345')
file=open('f://ftpdownload/test.txt','wb')
ftp.retrbinary("RETR test.txt",file.write,1024)#從服務(wù)器上下載文件 1024字節(jié)一個塊
ftp.set_debuglevel(0)
ftp.close()
FTP服務(wù)器事件回調(diào)函數(shù):
class MyHandler(FTPHandler):
def on_connect(self):#鏈接時調(diào)用
print "%s:%s connected" % (self.remote_ip, self.remote_port)
def on_disconnect(self):#關(guān)閉連接是調(diào)用
# do something when client disconnects
pass
def on_login(self, username):#登錄時調(diào)用
# do something when user login
pass
def on_logout(self, username):#登出時調(diào)用
# do something when user logs out
pass
def on_file_sent(self, file):#文件下載后調(diào)用
# do something when a file has been sent
pass
def on_file_received(self, file):#文件上傳后調(diào)用
# do something when a file has been received
pass
def on_incomplete_file_sent(self, file):#下載文件時調(diào)用
# do something when a file is partially sent
pass
def on_incomplete_file_received(self, file):#上傳文件時調(diào)用
# remove partially uploaded files
import os
os.remove(file)
---------------------
作者:shu_8708
來源:CSDN
原文:https://blog.csdn.net/shu_8708/article/details/79000251
版權(quán)聲明:本文為博主原創(chuàng)文章,轉(zhuǎn)載請附上博文鏈接!