linux python脚本定时删除文件_Python脚本,定时删除归档日志文件

#!/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()

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值