1. 程式人生 > >Python搭建FTP伺服器

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)