python ftp上传下载文件

运行环境:
centos7上使用vsftp搭建ftp 服务器;
ftp 用户名user,密码xxxxxxx;
windows7 上运行python脚本,上传文件到ftp服务器和下载文件到本地;
提示:
ftp需要使用多个端口,请注意防火墙状态
vsftp配置pasv模式参考:

https://blog.csdn.net/newborn2012/article/details/15812821/
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
__author__ = 'bing'
 
from ftplib import  FTP
import os
 
class MyFTP:
    def __init__(self):
        '''ftp服务器主机IP,端口等配置'''
       
 
        self.ftp_host = '172.16.1.58'
        self.ftp_port = 21
        self.ftp_user = 'user'
        self.ftp_passwd = 'xxxxxxx'
        self.ftp = FTP()
 
 
    def get_ftp_host(self):
        return self.ftp_host
 
    def get_ftp_port(self):
        return self.ftp_port
 
    def get_ftp_user(self):
        return self.ftp_user
 
    def get_ftp_passwd(self):
        return self.ftp_passwd
 
    # 连接到ftp服务器
    def connect(self):
        print('is connecting to ftp server %s on %s' % (self.ftp_host, self.ftp_port))
        self.ftp.connect(self.ftp_host, self.ftp_port)
 
    # 登陆到ftp服务器
    def login(self):
        print('ready to login ftp server')
        self.ftp.login(self.ftp_user, self.ftp_passwd)
        print('login ftp server successfully')
        print(self.ftp.getwelcome())
 
    # 友好的关闭连接
    def quit(self):
        try:
            self.ftp.quit()
            print('colose ftp connection successfully')
        except Exception as e:
            print('%s' % e)
 
    # 上传文件夹
    def upload_folder(self, local_path='../screenshot_lib', remote_path='/home/testacc'):
        local_path = local_path.strip() # 以防万一,去除首尾空格
        local_path = local_path.rstrip('/') # 去除右部 /
        local_path = local_path.rstrip('\\') # 去除右部 \\
        remote_path = remote_path.strip()
        remote_path = remote_path.rstrip('/')
        remote_path = remote_path.rstrip('\\')
        self.ftp.cwd(remote_path) 
        remote_path = remote_path.replace('\\', '/') # 转为linux标准路径
       
 
        sub_items = os.listdir(local_path)
        for sub_item in sub_items:
            sub_item_path = os.path.join(local_path, sub_item)
            sub_remote_path = os.path.join(remote_path,sub_item)
            sub_remote_path = sub_remote_path.replace('\\', '/') # 转为linux标准路径

            try:
                self.ftp.mkd(sub_remote_path)
            except:
                #print('dir: %s already exists' % last_dir)
                pass
            
            item_files = os.listdir(sub_item_path)
            for item_file in item_files:
                sub_item_file = os.path.join(sub_item_path,item_file)
                print("=============="+sub_item_file,sub_remote_path)
                self.upload_file(sub_item_file, sub_remote_path)
 
    # 上传文件
    def upload_file(self, src_file_path, remote_path):
        remote_file_name = os.path.split(src_file_path)[1]
        remote_path = remote_path + '/' + remote_file_name
        try: #如果文件不存在,调用file.size(filename)会报错
            if self.ftp.size(remote_path) != None:
                print("文件%s已存在" % remote_path)
                return
        except Exception as e:
            pass
 
        with open(src_file_path, 'rb') as file_handler:
            try:
                self.ftp.storbinary('STOR %s' % remote_path , file_handler)
                print('文件:%s 已经上传到ftp' % src_file_path)
            except:
                print('文件:%s 已经上传失败' % src_file_path)

 
 
    # 下载目录
    def download_dir(self,local_path, remote_path):
        local_path = local_path.strip() # 以防万一,去除首尾空格
        remote_path = remote_path.strip()
        remote_path = remote_path.rstrip('/')
        remote_path = remote_path.rstrip('\\')
 
        #last_dir = os.path.basename(remote_path)
        #local_path = os.path.join(local_path, last_dir)
        local_path = local_path.replace('/', '\\') # 转为Windows标准路径
        # 如果本地客户端不存在该路径,则创建对应路径下的目录
        if not os.path.isdir(local_path):
            os.mkdir(local_path)
 
        sub_items = self.ftp.nlst(remote_path)
        for sub_item in sub_items:
            local_item_path = os.path.basename(sub_item)
            local_item_path = os.path.join(local_path,local_item_path)
            local_item_path = local_item_path.replace('/', '\\') # 转为Windows标准路径
            if not os.path.isdir(local_item_path):
                os.mkdir(local_item_path)
            remote_item_files = self.ftp.nlst(sub_item)
            for remote_item_file in remote_item_files:
                print(local_item_path,remote_item_file)
                self.download_file(local_item_path, remote_item_file)
          
        
        
    def download_file(self, local_path, remote_file_path):
    
        last_file_name = os.path.split(remote_file_path)[1]
        local_file_path = os.path.join(local_path, last_file_name)
 

        if os.path.isfile(local_file_path):
            local_file_path = local_file_path.replace('\\', '/')
            print('文件:%s 已存在' % local_file_path)
            return
 
        with open(local_file_path, 'wb') as file_handle:
            self.ftp.retrbinary('RETR %s' % remote_file_path, file_handle.write)
            
if __name__ == '__main__':
    ftp = MyFTP()
    ftp.connect()
    ftp.login()
    ftp.upload_folder('C:\\resources\\','/resources/')
    ftp.download_dir('C:\\resources\\', '/resources/')
    ftp.quit()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值