python向ftp上传文件,解决中文问题

# coding: UTF-8
import os
import sys
import salt.client
import salt.config
import time
from ftplib import FTP, FTP_TLS
import json
from subprocess import Popen, PIPE, STDOUT

agent_ids = agent_ip.split',')
if '{' in sys_type:
    sys_types=json.loadssys_type)
else:
    sys_types={}
    for i in agent_ids:
        sys_types.update{i:sys_type})


def get_source_file_pathsource_file_path,agent_id):
    global sys_types
    sys_type=sys_types.getagent_id)
    if sys_type == 'windows':
        if source_file_path.startswith'/'):
            source_file_path='c:'+source_file_path
        source_file_path = source_file_path.replace'\\', '/')
        source_file_path = source_file_path.replace'\', '/')
        source_file_path=source_file_path.decode'gbk')
        print source_file_path
    else:
        if isinstancesource_file_path, unicode):
            source_file_path = source_file_path.encode'utf8')
    file_paths = source_file_path.split'
')
    return file_paths

if isinstanceftp_dir, unicode):
    ftp_dir = ftp_dir.encode'utf8')

BASE_URL = os.getenv'ANT_BASEURL')

fail = []
success = []


def agent_to_proxy):
    global agent_ids, source_file_path, success, fail, BASE_URL
    proxy_path = os.getenv'ANT_MODULE_ROOT', '')
    master_conf = os.path.joinproxy_path, 'conf', 'master')
    if not os.path.existsmaster_conf):
        print'Proxy 路径不正确 {}'.formatproxy_path))
        sys.exit1)
    opts = salt.config.client_configmaster_conf)
    LocalClient = salt.client.LocalClientmaster_conf)
    CACHE_DIR = opts['cachedir']
    for agent_id in agent_ids:
        file_paths=get_source_file_pathsource_file_path, agent_id)
        print file_paths
        ret = LocalClient.cmdagent_id, 'cp.push', file_paths, expr_form='list')
        no_exist_hosts = setret.keys)) - setagent_ids)
        print no_exist_hosts
        if no_exist_hosts:
            print'异常:{} agent 不存在'.formatlistno_exist_hosts)))
            sys.exit1)
        for file_path in file_paths:
            for host, status in ret.iteritems):
                if status is True:
                    proxy_file_path = os.path.joinCACHE_DIR, 'minions', host, 'files',
                                                   file_path.lstrip'/'))
                    res = proxy_to_ftpproxy_file_path)
                    if res:
                        print file_path, '上传成功'
                    else:
                        fail.append'{}:{}'.formathost, file_path))
                elif status is False:
                    print'{}:{} 上传失败,可能文件不存在'.formathost, file_path))
                    fail.append'{}:{}'.formathost, file_path))
                else:
                    print'异常:{}:{} 上传失败,{}'.formathost, file_path, status))
                    fail.append'{}:{}'.formathost, file_path))


def _conn_ftpuser, passwd):
    global ftp_host, ftp_port, connect_type
    conn = False

    ispasv = False if user in None, 'false') else True

    ftp_url = ftp_host
    connect_type = connect_type.lower)
    port = ftp_port
    try:
        if ':' in ftp_url:
            conn = True
            ftp_url, port = ftp_url.split':')

        if conn:
            ftp = FTP)
            ftp.connecthost=strftp_url), port=intport))
        else:
            ftp = FTPftp_url)
        ftp.loginuser, passwd)

    except Exception as e:
        if 'requires SSL.' in '{}'.formate):
            try:
                if conn:
                    ftp = FTP_TLS)
                    ftp.connecthost=ftp_url, port=intport))
                else:
                    ftp = FTP_TLSftp_url)
                ftp.loginuser, passwd)
            except Exception as e:
                print e
                sys.exit1)
        else:
            print e
            sys.exit1)
    return ftp, ispasv


def proxy_to_ftpproxy_file_path):
    global username, password, ftp_dir
    ftp, ispasv = _conn_ftpusername, password)
    ftp.encoding = "utf-8"
    try:
        ftp.set_pasvispasv)
        # ftp.retrlines'LIST')
    except:
        ftp.set_pasvnot ispasv)
    now_path = ftp.pwd)
    print now_path

    if ftp_dir and ftp_dir != '/':
        try:
            ftp.cwdftp_dir)
        except:
            new_path = os.path.joinnow_path, ftp_dir.lstrip'/'))
            print new_path
            ftp.mkdnew_path)
            ftp.cwdnew_path)

    try:
        ftp.renameos.path.basenameproxy_file_path).decode"utf8").encode'gbk'), os.path.basenameproxy_file_path).decode"utf8").encode'gbk')+'.'+time.strftime'%Y-%m-%d_%H:%M:%S'))
    except:
        pass
    print proxy_file_path
    with openproxy_file_path, 'rb') as f_:
        result = ftp.storbinary'STOR %s' % os.path.basenameproxy_file_path).decode"utf8").encode'gbk'), f_)

    ftp.close)
    if 'Transfer complete.' in result:
        return True
    else:
        return False


try:
    agent_to_proxy)
    if success:
        print '文件传输成功:{}'.format','.joinsuccess))
    if fail:
        print '文件传输失败:{}'.format','.joinfail))
        sys.exit1)
except Exception as e:
    print e
    sys.exit1)

  

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注