基于Python实现Ftp文件上传,下载

 

by:授客 QQ1033553122

测试环境:

Ftp客户端:Windows平台

Ftp服务器:Linux平台

Python版本:Python 2.7.6

 

实现功能:

支持FTP文件上传、下载,可以上传目录(分区除外),也可以上传单个文件;可以下载整个目录(/根目录除外),也可以下载单个文件

 

实践代码:

#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
__author__ = 'shouke'
 
from ftplib import  FTP
import  ConfigParser
import os
 
class MyFTP:
    def __init__(self, ftp_conf):
        '''ftp服务器主机IP,端口等配置'''
        config = ConfigParser.ConfigParser()
        config.read(ftp_conf)
 
        self.ftp_host = config.get('FTP', 'ftp_host')
        self.ftp_port = config.get('FTP', 'ftp_port')
        self.ftp_user = config.get('FTP', 'ftp_user')
        self.ftp_passwd = config.get('FTP', 'ftp_passwd')
        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'):
        if not os.path.isdir(local_path):
            print('出错了,请选择要上传的文件夹')
            return
        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)
 
        last_dir = os.path.basename(local_path)
        remote_path = os.path.join(remote_path, last_dir)
        remote_path = remote_path.replace('\\', '/') # 转为linux标准路径
        # 如果ftp服务器上不存在该路径,则创建对应路径下的目录
        try:
            self.ftp.mkd(last_dir)
        except:
            #print('dir: %s already exists' % last_dir)
            pass
 
        sub_items = os.listdir(local_path)
        for sub_item in sub_items:
            sub_item_path = os.path.join(local_path, sub_item)
            if os.path.isdir(sub_item_path): #如果子项目为目录
                self.upload_folder(sub_item_path, remote_path)
            else:
                self.upload_file(sub_item_path, 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:
             self.ftp.storbinary('STOR %s' % remote_path , file_handler)
             print('文件:%s 已经上传到ftp' % src_file_path)
 
 
    # 下载目录
    def download_dir(self,local_path, remote_path):
        if os.path.isfile(local_path):
            print('出错了,请选择文件保存位置')
            return
        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:
            try:
                self.ftp.cwd(sub_item) #如果子项目为目录
                self.download_dir(local_path, sub_item)
            except Exception: # 非目录
                self.download_file(local_path, sub_item)
 
    def download_file(self, local_path, remote_file_path):

if os.path.isdir(local_file_path):

             print('请选择文件保存目录路径')
             return
                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('./config/ftp.conf')
    ftp.connect()
    ftp.login()
    ftp.upload_folder()
    ftp.upload_folder('E:\\dir1')
    # ftp.upload_folder('E:\\dir1\\')
    # ftp.upload_folder('E:/dir1/')
    # ftp.download_dir('E:\\', '/home/testacc')
    # ftp.download_dir('E:/', '/home/testacc')
    ftp.download_file('E:\\', '/home/testacc/testfile')
    ftp.quit()
 
ftp.conf配置如下:
[FTP]
ftp_host = 192.168.1.103
ftp_port = 21
ftp_user = testacc
ftp_passwd = testacc
 

测试数据如下:


pdf版本下载地址:基于Python实现Ftp文件上传,下载.pdf

Python 基于Python实现Ftp文件上传,下载的更多相关文章

  1. 【FTP】FTP文件上传下载-支持断点续传

    Jar包:apache的commons-net包: 支持断点续传 支持进度监控(有时出不来,搞不清原因) 相关知识点 编码格式: UTF-8等; 文件类型: 包括[BINARY_FILE_TYPE(常 ...

  2. java/struts/Servlet文件下载与ftp文件上传下载

    1.前端代码 使用超链接到Struts的Action或Servlet <a target="_blank" href="ftpFileAction!download ...

  3. python 实现远端ftp文件上传下载

    python 实现ftp上传下载 * 脚本需要传入两个参数,参数1为需要从远端ftp站点下载文件名称,参数2为已知需要下载的文件md5值,文件下载完成后会自动进行md5值校验 * 运行示例 [root ...

  4. 4.1 - FTP文件上传下载

    题目:开发一个支持多用户同时在线的FTP程序要求:1.用户加密认证2.允许同时多用户登录3.每个用户有自己的家目录,且只能访问自己的家目录4.对用户进行磁盘配额,每个用户的可用空间不同5.允许用户在f ...

  5. java实现ftp文件上传下载,解决慢,中文乱码,多个文件下载等问题

    //文件上传 public static boolean uploadToFTP(String url,int port,String username,String password,String ...

  6. ftp文件上传下载命令

    介绍:从本地以用户wasqry登录的机器1*.1**.21.67上通过ftp远程登录到ftp服务器上,登录用户名是lte****,以下为使用该连接做的实验.  查看远程ftp服务器上用户lte**** ...

  7. ftp文件上传下载实用命令

    连接 >ftp yourhost >user yourusername >password your password 顺利的话连接成功 >dir ;获取remote目录列表 ...

  8. Java 利用Apache Commons Net 实现 FTP文件上传下载

    package woxingwosu; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import ...

  9. 3.2 - FTP文件上传下载

    题目:开发一个支持多用户同时在线的FTP程序要求:1.用户加密认证2.允许同时多用户登录3.每个用户有自己的家目录,且只能访问自己的家目录4.对用户进行磁盘配额,每个用户的可用空间不同5.允许用户在f ...

随机推荐

  1. android设备不识别awk命令,缺少busybox

    android设备不识别awk命令,缺少busybox 一.什么是BusyBox ? BusyBox 是标准 Linux 工具的一个单个可执行实现.BusyBox 包含了一些简单的工具,例如 cat ...

  2. [Umbraco] macro(宏)在umbraco中的作用

    macro在umbraco中是一个核心的应用,它是模板页中用于动态加载内容的标签(模板指令),宏可以是基于XSLT文件创建,亦可以是基于ASP.NET用户控件创建 在develop下的Macros中创 ...

  3. android屏幕密度规律及dp px转换

    px和dp(sp) 之间转化公式: 1  乘以(dp转px)或者除以(px转dp) scal缩放因子,在上浮0.5f /** * 密度转换像素 * */ public static int dip2p ...

  4. Azure Storage架构介绍

    Windows Azure Storage由三个重要部分或者说三种存储数据服务组成,它们是:Windows Azure Blob.Windows Azure Table和Windows Azure Q ...

  5. Is it possible to display icons in a PopupMenu?

    I really like the new PopupMenu we got in 3.0, but I just can't display any icons next to the menu i ...

  6. 深入浅出zeptojs中tap事件

    1.tap事件实现 zepto 源码里面看关于tap的实现方法: $(document).ready(function(){ var now, delta, deltaX = 0, deltaY = ...

  7. 如何恢复windows的exe文件的默认打开方式

    事情由来: 有一次在用一个播放器选择打开视频文件的时候,意外的手贱点击打来了 exe 文件,之后戏剧性的恶心开始了,首先当然是打开失败,接着整个桌面的 exe 文件全部被替换成那个播放器的图标,然后所 ...

  8. spring boot 与 thymeleaf (4): 基本对象、工具类对象

    如果在前台, 我需要获取session中的信息, 或者需要获取url中的参数信息, 是不是需要在后台手动处理好, 然后放到Model中去, 在前台通过${}来取呢? 当然, 这种方式, 是可以的, 但 ...

  9. mongo学习使用记录2 spring data

    spring data mongo 打印mongo NoSql语句 log4j.properties log4j.rootLogger=INFO, stdout log4j.logger.org.sp ...

  10. INTEST/EXTEST SCAN 的学习

    intest scan的一些基本知识.INTEST scan指的是对IP 内部的scan cell的扫描测试,针对IP内部的flip-flop进行shift/capture的操作.和INTEST SC ...