码迷,mamicode.com
首页 > 编程语言 > 详细

Python下使用ftplib上传文件到ftp上

时间:2016-11-24 08:12:14      阅读:145      评论:0      收藏:0      [点我收藏+]

标签:compile   pat   子目录   path   process   env   多级   open   没有   

生产情况:tomcat下业务log备份,目录分多级,然后对应目录格式放到ftp上;所以,结构上 我就是一级一级目录进行判断(因为我没有找到在ftp一次判断其子目录是否存在),还有一个low点就是我没有找到怎样一次性的调用ftp的login因为现在每次判断都需要登录一下,最终功能是实现了;想着先贴出来

#!/usr/local/bin/python3.5
###Description: 上传业务log到FTP199
###Author: Tonny.Deng
###DateTime: 2016-11-22
import os,sys,shutil,time,datetime,re,socket,subprocess
import ftplib
##########################
backup_dir = "/dockerlogs/"
ip_addr = socket.gethostbyname(socket.gethostname())
ports = sorted(os.listdir(backup_dir))
yesterday = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
thirday = (datetime.datetime.now() - datetime.timedelta(days=2)).strftime("%Y-%m-%d")
###############取log文件
pattern = re.compile(r‘‘ + thirday + ‘*.log$‘ )
#pattern = re.compile(r‘‘ + thirday + ‘*.log‘ )
###############取服务端口列表目录
for port in (ports):
   port_dir = backup_dir + port
   ftp_dir = ip_addr + "/" + port
##############判断ftp上是否有对应目录,没有则创建,此次判断是两个目录 如:192.168.20.130/8000 这两个目录是否存在
   ftp = ftplib.FTP("192.xxxxx")
   ftp.login("sxxxxxxxxxxxxxx","xxxxxxxxx,10)
   try:
      ftp.mkd(ip_addr)
      ftp.cwd(ip_addr)
      try:
         ftp.mkd(port)
         ftp.quit()
      except ftplib.error_perm:
         ftp.quit()
   except ftplib.error_perm:
      ftp.cwd(ip_addr)
      try:
         ftp.mkd(port)
         ftp.quit()
      except ftplib.error_perm:
         ftp.quit()
##############取端口目录下的service目录
   for services in sorted(os.listdir(port_dir)):
      services_dir = port_dir + "/" + services
##############判断services目录是否存在,即第三级 如:192.168.20.130/8000/yunwei
      ftp = ftplib.FTP("192.xxxxxx")
      ftp.login("syxxxxxx","sxxxxxx",10)
      ftp.cwd(ftp_dir)
      try:
         ftp.mkd(services)
      except ftplib.error_perm:
         ftp.quit()
#############遍历service目录中的符合的文件
      for file in sorted(os.listdir(services_dir)):
         match = pattern.search(file)
         if match:
#############匹配到文件后进行 文件名 更换操作,方便上传
            ftpdir_service = ftp_dir + "/" + services
#############登录到ftp上的对应目录,准备上传
            ftp = ftplib.FTP("19xxxxxxxxxx")
            ftp.login("sxxxxx","syxxxxxxx",10)
            ftp.cwd(ftpdir_service)
            filename = services_dir + "/" + file
#############上传压缩文件到ftp
            os.environ[‘filename‘] = str(filename)
            os.system(‘gzip $filename‘)
            filename_gz = filename +  ".gz"
#############只读模式打开本地需要上传的文件
            filename_put = open(filename_gz,‘rb‘)
            ftp.storbinary(‘STOR %s‘ % os.path.basename(filename_gz),filename_put)
            ftp.nlst()

  

Python下使用ftplib上传文件到ftp上

标签:compile   pat   子目录   path   process   env   多级   open   没有   

原文地址:http://www.cnblogs.com/tony-d/p/6095675.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!