使用Python 实现ftp文件上传、下载

python的ftplib模块中封装好了实现FTP传输的功能,直接导入使用。

server端

from pyftpdlib.authorizers import DummyAuthorizer
from pyftpdlib.handlers import FTPHandler
from pyftpdlib.servers import FTPServer

# 新建一个用户组
authorizer = DummyAuthorizer()
# 将用户名,密码,指定目录,权限 添加到里面
authorizer.add_user("username", "password", "file", perm="elradfmwM")  
# 这个是添加匿名用户,任何人都可以访问,如果去掉的话,需要输入用户名和密码,可以自己尝试
authorizer.add_anonymous("file")

handler = FTPHandler
handler.authorizer = authorizer
# 开启服务器
server = FTPServer(("", port), handler)
server.serve_forever()

client端

from ftplib import FTP
import datetime
def ftpconnect(host, username, password):
    ftp = FTP()
    ftp.set_debuglevel(2)
    ftp.connect(host, 21) #填自己服务的端口号 一般是21
    ftp.login(username, password)
    ftp.set_pasv(False) #主动模式
    print(ftp.getwelcome())
    return ftp

def downloadfile(ftp, remotepath, localpath):
    # 从ftp下载文件
    bufsize = 1024
    fp = open(localpath, 'wb')
    ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize)
    ftp.set_debuglevel(0)
    fp.close()


def uploadfile(ftp, localpath, remotepath):
    # 从本地上传文件到ftp
    bufsize = 1024 
    fp = open(localpath, 'rb')
    ftp.storbinary('STOR ' + remotepath, fp, bufsize)
    ftp.set_debuglevel(0)
    fp.close()

if __name__ == "__main__":
    ftp = ftpconnect("ip", "username", "password")
    local_file = '本地上传的文件路径'
    target_file = '服务器生成的文件路径'
    uploadfile(ftp, local_file, target_file)
    # downloadfile(ftp, "服务器文件路径","本地存储路径")
    ftp.quit()

python3以后ftp默认是被动模式,如果需要上传文件需要添加ftp.set_pasv(False),不然会连接超时。

原文地址:https://www.cnblogs.com/Pynu/p/15014896.html