#!/usr/bin/env python
import os
#打包模块
import tarfile
import time
#文件处理模块
import shutil
import logging
cwd = '/app/applogs'
servername = ['os','agentserver']
Hflag = ['error.log','log.log']
backdir="/app/backup"
#定义日志
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s %(message)s ',
datefmt='%a,%d %b %Y %H:%M:%S',
filename='logfile.log',
filemode='w')
#获取目录下文件并且存储为列表
def getlist(Hname,cwd):
listname = []
flist = os.listdir(cwd)
for name in flist:
if Hname in name:
listname.append(name)
return sorted(listname)
#打包并且删除原来文件
def Maketar(tarname,filelist):
tar = tarfile.open(tarname,"w:gz")
for name in filelist:
tar.add(name)
os.remove(name)
tar.close()
for server in servername:
#拼接路径
if cwd.endswith('/'):
tempdir = '{0}{1}'.format(cwd,server)
else:
tempdir = '{0}/{1}'.format(cwd,server)
for flag in Hflag:
lists = getlist(flag+'.',tempdir)
logging.info('Get list Now,The directory is {0},All of file are {1}'.format(tempdir,lists))
while True:
if len(lists) >= 10:
templist = lists[:10]
lists = lists[10:]
tarname = '{0}{1}_{2}.tar.gz'.format(flag,templist[0][-10:],templist[-1][-5:])
os.chdir(tempdir)
logging.info('Compress file now,The directory is {0},Compressed filelist are {1}'.format(tempdir,templist))
Maketar(tarname,templist)
else:
break
mflist = getlist('tar.gz',tempdir)
logging.info('The files endfix with tar.gz are {0}'.format(mflist))
os.chdir(tempdir)
try:
for tarf in mflist:
if backdir.endswith('/'):
bckdir = '{0}{1}'.format(backdir,server)
else:
bckdir = '{0}/{1}'.format(backdir,server)
if not os.path.exists(bckdir):
logging.info('Now The directory {} will be created!'.format(bckdir))
os.makedirs(bckdir)
days = (time.time() - os.path.getmtime(tarf)) // 86400
if days >= 30:
logging.info('The file {0} will be moved to {1}'.format(tarf,bckdir))
shutil.move(tarf,bckdir)
except shutil.Error:
logging.info('The file of tar.gz exists')
写一个日志打包备份的脚本
猜你喜欢
转载自blog.csdn.net/qq_44370158/article/details/131548760
今日推荐
周排行