免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 11646 | 回复: 9
打印 上一主题 下一主题

python下载FTP上面的文件夹 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2011-06-14 16:58 |只看该作者 |倒序浏览
FTP指定文件夹里的内容下载到本地,文件夹到底有多少层不知道

这个地方用递归我知道,但是写了几次都报错

希望哪位大侠贴下代码,十分感谢了

论坛徽章:
0
2 [报告]
发表于 2011-06-14 17:24 |只看该作者
本帖最后由 iamacnhero 于 2011-06-14 17:27 编辑

ftp_mirror.py
  1. # -*- encoding: utf8 -*-
  2. import os
  3. import sys
  4. import ftplib

  5. class FTPSync(object):
  6.     def __init__(self):
  7.         self.conn = ftplib.FTP('10.22.14.23', 'user', 'pass')
  8.         self.conn.cwd('/')        # 远端FTP目录
  9.         os.chdir('/data/')                # 本地下载目录

  10.     def get_dirs_files(self):
  11.         u''' 得到当前目录和文件, 放入dir_res列表 '''
  12.         dir_res = []
  13.         self.conn.dir('.', dir_res.append)
  14.         files = [f.split(None, 8)[-1] for f in dir_res if f.startswith('-')]
  15.         dirs = [f.split(None, 8)[-1] for f in dir_res if f.startswith('d')]
  16.         return (files, dirs)

  17.     def walk(self, next_dir):
  18.         print 'Walking to', next_dir
  19.         self.conn.cwd(next_dir)
  20.         try:
  21.             os.mkdir(next_dir)
  22.         except OSError:
  23.             pass
  24.         os.chdir(next_dir)

  25.         ftp_curr_dir = self.conn.pwd()
  26.         local_curr_dir = os.getcwd()

  27.         files, dirs = self.get_dirs_files()
  28.         print "FILES: ", files
  29.         print "DIRS: ", dirs
  30.         for f in files:
  31.             print next_dir, ':', f
  32.             outf = open(f, 'wb')
  33.             try:
  34.                 self.conn.retrbinary('RETR %s' % f, outf.write)
  35.             finally:
  36.                 outf.close()
  37.         for d in dirs:
  38.             os.chdir(local_curr_dir)
  39.             self.conn.cwd(ftp_curr_dir)
  40.             self.walk(d)

  41.     def run(self):
  42.         self.walk('.')

  43. def main():
  44.     f = FTPSync()
  45.     f.run()

  46. if __name__ == '__main__':
  47.     main()
复制代码

论坛徽章:
0
3 [报告]
发表于 2011-06-15 09:21 |只看该作者
回复 2# iamacnhero


        def get_dirs_files(self):
        print('得到当前目录和文件, 放入dir_res列表 ')
        dir_res = []
        self.conn.dir('.', dir_res.append)
        
        print(dir_res)
        files = [f.split(None, [-1] for f in dir_res if f.startswith('-')]
        print(files)
        dirs = [f.split(None, [-1] for f in dir_res if f.startswith('d')]
        print(dirs)
        return (files, dirs)

我是用3.2写的,运行出来没有取出结果啊,files和dirs是空的.........

这个打印出来的结果是
得到当前目录和文件, 放入dir_res列表
['06-08-11  15:50         <DIR>          .', '06-08-11  15:50         <DIR>          ..', '06-08-11  15:51                  14443 collog_report_result.txt', '06-08-11  15:50         <DIR>          SEC-LOG', '06-08-11  15:50         <DIR>          BSC-LOG', '06-08-11  15:51         <DIR>          CFG-LOG', '06-08-11  15:50         <DIR>          PFM-LOG', '06-08-11  15:50         <DIR>          ALM-LOG', '06-08-11  15:50         <DIR>          OPT-LOG', '06-08-11  15:50         <DIR>          SINGLE-BAM']
[]
[]

论坛徽章:
0
4 [报告]
发表于 2011-06-15 10:13 |只看该作者
回复 2# iamacnhero


            print('06-08-11  15:51                  14443 collog_report_result.txt'.split(None, [-1])
        print('06-08-11  15:51                  14443 collog_report_result.txt'.find('<DIR>'))
        #sys.exit()
        dir_res = []
        self.conn.dir('.', dir_res.append)
        
   
        
        files = [f.split(None, [-1] for f in dir_res if f.find('<DIR>')=='-1']

        print(files)
        dirs = [f.split(None, [-1] for f in dir_res if f.find('<DIR>')!='-1']
   
        return (files, dirs)


这是我做修改后的,不过成了死循环了,而且还是不出任何files

论坛徽章:
0
5 [报告]
发表于 2011-06-15 11:48 |只看该作者
回复 2# iamacnhero


            dir_res = []
        conn.dir('.', dir_res.append)  
        files = [f.split(None, [-1] for f in dir_res if f.find('<DIR>')==-1]#隐患
     dirs = [f.split(None, [-1] for f in dir_res if f.find('<DIR>')>=0][2:]

修改成这样就OK了


不过这里用空格来分割不合适,应为有文件和文件夹中间是有空格的

论坛徽章:
0
6 [报告]
发表于 2011-06-15 11:51 |只看该作者
我运行是成功的,能把你的源代码发来吗?

论坛徽章:
0
7 [报告]
发表于 2011-06-15 12:05 |只看该作者
  1. # -*- coding: cp936 -*-
  2. #!/usr/bin/env python

  3. '''
  4. Created on 2011-6-2

  5. @author: zKF30352
  6. '''



  7. from ftplib import FTP
  8. import shutil, sys, os, time
  9. from datetime import datetime
  10. from xml.etree import ElementTree as ET
  11. from Dev_Data.LoadXml import loadItem






  12. def main(host,ftpuser,pwd,traitname,startTime,logtype):

  13.     #生成本地路径
  14.     currentDir = os.path.dirname(sys.argv[0])
  15.    
  16.     ccfile = open(currentDir+'\\Dev_Cfg\\resultPath.txt', 'r')
  17.     txns = ccfile.read()   
  18.     ccfile.close()
  19.    
  20.     gtrBgnTime = startTime.replace(":", "_").replace('-', '_').replace(' ', '_')
  21.     filepath = txns + 'log\\'+gtrBgnTime+traitname+'\\'+logtype+'\\'
  22.     if not os.path.exists(filepath):     
  23.         os.makedirs(filepath)
  24.    
  25.    
  26.    
  27.     #连接到FTP   
  28.     try:   
  29.         conn = FTP(host, ftpuser, pwd)
  30.     except:
  31.         print('FTP连接失败')
  32.     #获取xml中配置的下载路径   
  33.     fadName =getXml(logtype)
  34.     conn.cwd(fadName)  
  35.       
  36.     os.chdir(filepath)  

  37.    
  38.     walk(conn,'.')
  39.    


  40.    
  41.    
  42.    
  43.    
  44. def walk(conn, next_dir):
  45.         #next_dir路径,下级目录的路径
  46.         conn.cwd(next_dir)
  47.         print(next_dir)
  48.         try:
  49.             os.mkdir(next_dir)#这个是在当前工作路径创建文件夹
  50.         except OSError:
  51.             pass
  52.         os.chdir(next_dir)#切换到当前路径为工作空间

  53.         ftp_curr_dir = conn.pwd()
  54.         local_curr_dir = os.getcwd()


  55.         dir_res = []
  56.         conn.dir('.', dir_res.append)  
  57.    
  58.         files = [f.split(None, 8)[-1] for f in dir_res if f.find('<DIR>')==-1]#隐患
  59.         dirs = [f.split(None, 8)[-1] for f in dir_res if f.find('<DIR>')>=0][2:]

  60.   
  61.         for f in files:
  62.             outf = open(f, 'wb')
  63.             try:
  64.                 conn.retrbinary('RETR %s' % f, outf.write)

  65.             finally:
  66.                 outf.close()
  67.         print(local_curr_dir)
  68.         print(ftp_curr_dir)
  69.         for d in dirs:
  70.             os.chdir(local_curr_dir)
  71.             conn.cwd(ftp_curr_dir)
  72.             walk(conn,d)
  73.             
  74. def getXml(logtype):
  75.     #获取自动化运行结果目录
  76.     currentDir = os.path.dirname(sys.argv[0])
  77.    
  78.     xmlPath = currentDir + "\\Dev_Cfg\\LOG_CFG.xml"
  79.     xmlTree = ET.parse(xmlPath)
  80.     fadName = loadItem(xmlTree, logtype+"/name")           #日志名
  81.    
  82.     return fadName
  83.         




  84. if __name__ == '__main__':
  85.     print('------------------------日志生成开始-----------------------------')
  86.     ftphost ='10.141.149.74'
  87.     ftpusr='FtpUsr'
  88.     ftppwd='111111'
  89.   
  90.     #生成fad日志
  91.     startTime = datetime.now().strftime(format="%Y-%m-%d %H:%M:%S")
  92.     traitname=sys.argv[1]#特性名称

  93.     #生成fad日志
  94.     logtype="fad"
  95.     main(ftphost,ftpusr,ftppwd,traitname,startTime,logtype)
  96.     #生成fam日志
  97.     logtype="fam"
  98.     main(ftphost,ftpusr,ftppwd,traitname,startTime,logtype)
  99.     #生成col日志
  100.     logtype='collog'
  101.     main(ftphost,ftpusr,ftppwd,traitname,startTime,logtype)
  102.    
  103.     print('------------------------日志生成结束-----------------------------')
复制代码

论坛徽章:
0
8 [报告]
发表于 2011-06-15 13:58 |只看该作者
你用的是 Windows的FTP,并且使用的是python 3?

论坛徽章:
0
9 [报告]
发表于 2011-06-15 14:31 |只看该作者
回复 8# iamacnhero


    硬件使用的linux,我是直接使用windows访问linux上的FTP服务器,大概就是这样的

论坛徽章:
0
10 [报告]
发表于 2011-06-15 16:34 |只看该作者
我测试用的是Ubuntu下的vsftp,脚本环境也是Ubuntu,python版本2.6,你的python版本是3.x ??
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP