python ftp 按目录结构上传下载

#!/usr/bin/python
# coding=utf-8
from ftplib import FTP
import time
import os


def __ftp_upload(ftp,local,remote,isDel=False):
    if os.path.isdir(local):
        for f in os.listdir(local):
            if os.path.isdir(local+f):
                try:
                    ftp.cwd(remote+f)
                except:
                    ftp.mkd(remote+f)
                print local+f
                __ftp_upload(ftp,local+f+'/',remote+f+'/',isDel)
            else:
                print remote+f
                print local+f
                fp = open(local+f, 'rb')
                ftp.storbinary('STOR ' + remote + f, fp, 4096)
                fp.close()
                if (isDel==True):
                    os.remove(local)
    else:
        fp = open(local+f, 'rb')
        ftp.storbinary('STOR ' + remote + f, fp, 4096)
        fp.close()
        if (isDel==True):
            os.remove(local)

def ftp_upload(host,port,username,password,local,remote,isDel=False):
    ftp = FTP()
    try:
        ftp.connect(host,port)
        ftp.login(username,password)
    except:
        return False
    try:
        __ftp_upload(ftp,local,remote,False)
    except Exception,e:
        print e
    ftp.close()
    return True

def ftp_download(host,port,username,password,local,remote):
    ftp = FTP()
    ftp.connect(host,port)
    ftp.login(username,password)
    ret = False
    try:
        if os.path.isdir(local):
            for f in ftp.dir(remote):
                fp = open(local+f, 'wb')
                ftp.retrbinary('RETR ' + remote + f, fp.write, 4096)
                fp.close()
        else:
            fp = open(local, 'wb')
            ftp.retrbinary('RETR ' + remote, fp.write, 4096)
            fp.close()
        ret = True
    except Exception,e:
        print ("download exception:\n",e)
    ftp.close()
    return ret



if __name__=='__main__':
    host = '*.*.*.*'
    port = '21'
    username = 'xxx'
    password = 'xxx'
    ftp_upload(host,port,username,password,'/home/pi/work/xx/','/home/ubuntu/xx/',False)
    print 'download'
    ftp_download(host,port,username,password,'/home/pi/work/xx/hh.txt','/home/ubuntu/xx/hh.txt')

只完成了按目录结构上传,下载还没弄好。留坑。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值