#!/usr/bin/env python3#-*- coding:utf-8 -*-
importmath,os,sys,timeimporttracebackimportsubprocessimportdatetime
...#定时任务脚本,删除归档日志文件
...#定义前一天的时间
theDayBeforeYesterday = (datetime.date.today() + datetime.timedelta(-2)).strftime('%Y-%m-%d')#定义文件路径
tomcatFilePath ={"/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/catalina":"删除tomcat归档日志文件->catalina","/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/host-manager":"删除tomcat归档日志文件->host-manager","/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/localhost":"删除tomcat归档日志文件->localhost","/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/localhost_access_log":"删除tomcat归档日志文件->localhost_access_log","/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/manager":"删除tomcat归档日志文件->manager"}#清除大于1G的文件
defclearTomcatArchiveLogs():print("<---删除tomcat归档日志文件--->")for filePath,message intomcatFilePath.items():
linuxCommand= "rm -rf" + filePath + "." + theDayBeforeYesterday + "*"responseMessage,responseCode=executeShell(linuxCommand)
checkResult(int(responseCode),message)print("<---删除tomcat归档日志文件--->")#执行linux命令获取返回结果与返回码
def executeShell(command,print_output=True,universal_newlines=True):print("需要执行的linux命令为["+command+"]")
p= subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=universal_newlines)ifprint_output:
output_array=[]whileTrue:
line=p.stdout.readline()if notline:breakoutput_array.append(line)
output="".join(output_array)else:
output=p.stdout.read()
p.wait()
errout=p.stderr.read()
p.stdout.close()
p.stderr.close()returnstr(output),str(p.returncode)#判断运行结果
defcheckResult(result,message):if result ==0:print(message+"执行成功")else:print(message+"执行失败")#异常的处理
defprintExcption(e):print("<---The Excption Begin--->")print('\n' * 1)
traceback.print_exc()print('\n' * 1)print("<---The Excption End--->")#最终执行的方法
deffinalExecute():print("<---The clearLargeFile.py Begin,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")print('\n' * 1)try:
clearTomcatArchiveLogs()exceptException as e:
printExcption(e)print('\n' * 1)print("<---The clearLargeFile.py End,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")#最终执行
finalExecute()