python连接ftp服务器上传下载文件

# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.

from datetime import datetime, date, timedelta
import os.path
import time
import os
import datetime
import zipfile
from ftplib import FTP

# 定义配置信息
Folder_path = "D:/temp"         # 被压缩的数据,文件夹形式
ZIP_Folder_path = "D:/ftizip/"  # 压缩好的数据临时存放的位置
FTP_file_path = "/"                       # 数据在FTP服务器上存放的位置
FTP_url = "192.168.0.158"                  # FTP服务器地址
FTP_port = 21                               # FTP服务端口号,一般默认21
username = ''                            # FTP服务器账号 匿名留空
password = ''                       # FTP服务器密码 匿名留空
# 解决zipfile压缩的文件路径太深问题

def get_zip_file(file_path, file_lists):
    file_s = os.listdir(file_path)
    for file in file_s:
        if os.path.isdir(file_path + '/' + file):
            print("file_path: ", os.path.isdir(file_path + '/' + file))
            get_zip_file(file_path + '/' + file, file_lists)
        else:
            file_lists.append(file_path + '/' + file)
def ftp_Upload(filename, folder, ftp_url, ftp_port):
    """
    :param filename: 待上传文件路径
    :param folder: 文件上传至FTP服务器上的存储目录
    :param ftp_url: FTP服务器IP
    :param ftp_port: 端口号,默认为21
    :return: status code
    """
    ftp = FTP()
    ftp.set_debuglevel(0)  # 设置调试级别,显示详细信息:2,关闭显示:0
    ftp.connect(ftp_url, ftp_port)
    ftp.login(username, password)  # 登录,如果匿名登录则用空串代替
    ftp.encoding = 'GB18030'
    # 切换到 FTP 服务器上的目录
    bufsize = 1024  # 设置缓冲块大小
    file_handler = open(filename, 'rb')
    res = -1
    now_time = datetime.datetime.now()
    end_time = now_time + datetime.timedelta(days=-1)
    ## 前一天时间只保留 年-月-日
    before_date = end_time.strftime('%Y%m%d')  # 格式化输出
    print("end date: ", before_date)
    res1 = os.path.join(folder, before_date)
    isExists = os.path.exists(before_date)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        ftp.mkd(res1)
        print(res1 + ' 创建成功')
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print(res1 + ' 目录已存在')
    ftp.cwd(res1)
    try:
        res = ftp.storbinary(f"STOR {os.path.basename(filename)}", file_handler, bufsize)  # upload file
    except Exception as e:
        print(f"except: {e}, cannot upload file: {ftp_url}:{ftp_port} {filename}")
    finally:
        ftp.set_debuglevel(0)  # 关闭debug信息
        file_handler.close()
        ftp.quit()
    return res

def zip_Folder(file_path, output_path, date):
    """
    :param file_path: 被压缩的源数据位置
    :param output_path: 压缩之后文件的存放路径
    :param date: 执行压缩的当前时间,datetime产生
    :return: 压缩文件的路径
    """
    ##压缩前一天的文件
    now_time = datetime.datetime.now()
    end_time = now_time + datetime.timedelta(days=-1)
    ## 前一天时间只保留 年-月-日
    before_date = end_time.strftime('%Y%m%d')  # 格式化输出
    startTime = time.perf_counter()
    desName = f"{output_path}" + before_date + ".zip"
    # 检查是否已经压缩过了
    if os.path.exists(desName):
        print(
            f"该文件已经存在,跳过压缩此文件,time:{datetime.datetime.now().strftime('%Y-%d-%m %H:%M:%S')},耗时:{(time.perf_counter() - startTime):.2f}s")
        return desName
    z = zipfile.ZipFile(desName, 'w', zipfile.ZIP_DEFLATED)
    file_lists = []
    file_path = Folder_path + '/' + before_date
    get_zip_file(file_path, file_lists)
    for file in file_lists:
        try:
            full_file_path = file
            compressed_file_path = file.split(file_path)[1]
            z.write(full_file_path, compressed_file_path)
        except Exception as e:
            print(f"except: {e}, 无法压缩文件: {file}")
    z.close()
    print(
        f"压缩完成,time:{datetime.datetime.now().strftime('%Y-%d-%m %H:%M:%S')},耗时:{(time.perf_counter() - startTime):.2f}s")
    return desName
# Press the green button in the gutter to run the script.

if __name__ == '__main__':
    Backup_Time = datetime.datetime.now()  # 产生当前执行备份时间,用作备份名字
    Zip_file_name = zip_Folder(Folder_path, ZIP_Folder_path, Backup_Time)  # 执行压缩文件夹
    ftp_Upload(Zip_file_name, FTP_file_path, FTP_url, FTP_port)
在这里插入代码片

你可能感兴趣的:(服务器,python,网络)