释放双眼,带上耳机,听听看~!
Python脚本,定时删除归档日志文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81 1# !/usr/bin/env python3
2# -*- coding:utf-8 -*-
3import math,os,sys,time
4import traceback
5import subprocess
6import datetime
7...
8#定时任务脚本,删除归档日志文件
9
10...
11#定义前一天的时间
12theDayBeforeYesterday = (datetime.date.today() + datetime.timedelta(-2)).strftime('%Y-%m-%d')
13
14#定义文件路径
15tomcatFilePath = {
16 "/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/catalina":"删除tomcat归档日志文件->catalina",
17 "/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/host-manager":"删除tomcat归档日志文件->host-manager",
18 "/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/localhost":"删除tomcat归档日志文件->localhost",
19 "/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/localhost_access_log":"删除tomcat归档日志文件->localhost_access_log",
20 "/usr/utils/tomcat9/apache-tomcat-9.0.14/logs/manager":"删除tomcat归档日志文件->manager"
21}
22
23#清除大于1G的文件
24def clearTomcatArchiveLogs():
25 print("<---删除tomcat归档日志文件--->")
26 for filePath,message in tomcatFilePath.items():
27 linuxCommand = "rm -rf " + filePath + "." + theDayBeforeYesterday + "*"
28 responseMessage,responseCode = executeShell(linuxCommand)
29 checkResult(int(responseCode),message)
30 print("<---删除tomcat归档日志文件--->")
31
32#执行linux命令获取返回结果与返回码
33def executeShell(command,print_output=True,universal_newlines=True):
34 print("需要执行的linux命令为["+command+"]")
35 p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, universal_newlines=universal_newlines)
36 if print_output:
37 output_array = []
38 while True:
39 line = p.stdout.readline()
40 if not line:
41 break
42 output_array.append(line)
43 output ="".join(output_array)
44 else:
45 output = p.stdout.read()
46 p.wait()
47 errout = p.stderr.read()
48 p.stdout.close()
49 p.stderr.close()
50 return str(output),str(p.returncode)
51
52#判断运行结果
53def checkResult(result,message):
54 if result == 0:
55 print(message+"执行成功")
56 else:
57 print(message+"执行失败")
58
59#异常的处理
60def printExcption(e):
61 print("<---The Excption Begin--->")
62 print('\n' * 1)
63 traceback.print_exc()
64 print('\n' * 1)
65 print("<---The Excption End--->")
66
67#最终执行的方法
68def finalExecute():
69 print("<---The clearLargeFile.py Begin,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")
70 print('\n' * 1)
71 try:
72 clearTomcatArchiveLogs()
73 except Exception as e:
74 printExcption(e)
75
76 print('\n' * 1)
77 print("<---The clearLargeFile.py End,the time is ["+datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')+"]--->")
78
79#最终执行
80finalExecute()
81
posted @
2018-12-25 21:34 故意养只喵叫顺儿 阅读(
…) 评论(
…) 编辑 收藏