Python腳本,定時刪除歸檔日志文件


# !/usr/bin/env python3
# -*- coding:utf-8 -*-  
import math,os,sys,time
import traceback
import subprocess
import datetime
...
#定時任務腳本,刪除歸檔日志文件

...
#定義前一天的時間
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的文件
def clearTomcatArchiveLogs():
    print("<---刪除tomcat歸檔日志文件--->")
    for filePath,message in tomcatFilePath.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)
    if print_output:
        output_array = []
        while True:
            line = p.stdout.readline()
            if not line:
                break
            output_array.append(line)
        output ="".join(output_array)
    else:
        output = p.stdout.read()
    p.wait()
    errout = p.stderr.read()
    p.stdout.close()
    p.stderr.close()
    return str(output),str(p.returncode)

#判斷運行結果
def checkResult(result,message):
    if result == 0:
        print(message+"執行成功")
    else:
        print(message+"執行失敗")

#異常的處理
def printExcption(e):
    print("<---The Excption Begin--->")
    print('\n' * 1)
    traceback.print_exc()
    print('\n' * 1)
    print("<---The Excption End--->")

#最終執行的方法
def finalExecute():
    print("<---The clearLargeFile.py Begin,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")
    print('\n' * 1)
    try:
        clearTomcatArchiveLogs()
    except Exception 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()

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM