python 数据文件上传到ftp服务器

场景:客户的某数据文件需要定时推送到一个第三方平台的ftp服务器上,第三方平台会对上传过来的数据文件进行解析。
一、通过FTP将文件上传到服务器,需要满足以下几个条件:

  1. 本服务器和ftp服务器是联通的
  2. 需要ftp服务器的IP,用户,密码,端口,ftp服务器文件要存放的路径

二、python代码如下

# -*- coding:utf-8 -*-

import logging
from ftplib import FTP


def ftp_connect(ftp_config):
    """

    :param ftp_config:
    :return:
    """
    host = ftp_config.get('host')
    username = ftp_config.get('username')
    password = ftp_config.get('password')
    port = ftp_config.get('port', 21)
    remote_path = ftp_config.get('remote_dir')
    if not (host and username and password and port):
        logging.error('请检查ftp配置,数据:{}'.format(ftp_config))
        print False
        return False, remote_path
    try:
        ftp = FTP()
        ftp.connect(host, port)
        resp = ftp.login(username, password)
        if '230' in resp:
            logging.info('FTP连接成功!')
            print True
            return ftp, remote_path
        print False
        logging.error('FTP连接失败,信息:{},请检查配置信息'.format(resp))
        return False, remote_path
    except Exception as e:
        logging.error('FTP连接抛出异常,异常信息:{}'.format(e))
        print False
    return False, remote_path


def upload_file(ftp, local_path, remote_path):
    """
    # 从本地上传文件到ftp
    :param ftp:
    :param local_path:
    :param remote_path:
    :return:
    """
    try:
        buff_size = 1024 * 1024 * 1024
        fp = open(local_path, 'rb')
        ftp.storbinary('STOR {}'.format(remote_path), fp, buff_size)
        fp.close()
        ftp.quit()
    except Exception as e:
        logging.error('发送文件error:{}'.format(e))


if __name__ == '__main__':
    ftp_config_data = {
        "host": "1.1.1.1",
        "username": "admin",
        "password": "123456",
        "port": 21,
        "remote_path": "/home/tmp/aa.txt"
    }
    local_path = '/xxx/xxx/aa.txt'
    ftp_obj, remote_path = ftp_connect(ftp_config=ftp_config_data)
    if ftp_obj is not False:
        upload_file(ftp_obj, local_path, remote_path)

你可能感兴趣的:(python,python,FTP)