Source

Simple_BackUP / backup.py

Full commit
#!/usr/bin/env python
# -*- coding: utf-8 -*-
##########################################################################
#BACKUP FILES company "AlieParusa"                                       #
##########################################################################
import xml.parsers.expat
import logging
import tarfile
import os
import modules
from datetime import datetime

#List of path backup from XML file with name is "path.xml"
def Path():
   paths={}
   paths_list = []
   def XMLlist(name, attrs):
       paths.update(attrs)
   filepaths=open("/usr/NAS/scripts/python/path.xml", "r")
   parse=xml.parsers.expat.ParserCreate()
   parse.StartElementHandler = XMLlist
   parse.ParseFile(filepaths)
   for i in paths.keys():
       paths_list.append(paths[i])	
   return paths
#Create tar archives
def Archive(paths):
    archivepath="/usr/NAS/backups/"
    date=datetime.now().strftime('%Y'"."'%m'"."'%d')
    #Create logg objects
    logging.basicConfig(filename=archivepath+'logs'+'_'+date+'.log',format='%(asctime)s %(message)s',level=logging.DEBUG)
    body=''
    year = int(datetime.now().strftime('%Y'))	
    moth = int(datetime.now().strftime('%m'))	
    day = int(datetime.now().strftime('%d'))	
    l_day = modules.ListDayArch(year,moth)
    for i in paths:
          if modules.Folderempty('/mnt/'+str(i))=='non_empty':
             logging.info('Start task: '+str(i))
             #Is  last task of the month?
	     if day ==  max(l_day):
                  archname=archivepath+str(i)+'_'+date+" mothcopy "+".tar" 	
             else:
                  archname=archivepath+str(i)+'_'+date+".tar"
             tar = tarfile.open(archname, "w")
             for root, dir, files in os.walk(str(paths[i])):
                 for file in files:
                     fullpath = os.path.join(root,file) 
                     try:
                             tar.add(fullpath)
                     except:
                             logging.warning("Error: "+fullpath)
             logging.info('Finish task: '+str(i))
             tar.close()
             # Email body include: name and size of file 'os.stat(archname).st_size'
             size = os.stat(archname).st_size/1048576
             body=body+'Job '+str(i)+' is done. '+'Size:'+str(size)+'Mb'+'\n'
          else:
             logging.warning("Error: "+str(i)+" mount error or folder is empty.") 
             body=body+str(i)+" mount error or folder is empty.\n"
            
#Send email          
    modules.Sendemail(fro_m='service@redsails.ru', to='backup@redsails.ru', body=body , subject='BackUP')
#Run processing
Archive(Path())
modules.Rotation(Path())