#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: nginx_log.py
Author : lihuabing
date: 2018/11/1
-------------------------------------------------
Change Activity:
2018/11/1:
-------------------------------------------------
"""
__author__ = 'lihuabing'
import os
def remove(pat): # pat:写入查询目录
import datetime
import time
f = list(os.listdir(pat))
for i in f:
a = "%s/%s" % (pat, i)
filedate = os.stat(a).st_mtime
datetime.datetime.fromtimestamp(filedate).strftime('%Y-%m-%d')
date1 = time.time()
num1 = (date1 - filedate)/60/60/24
if num1 > 365:
os.remove(a)
def patt():
access = "access.json"
access_time = "%s-%s.gz" % (access, tem())
return access, access_time
def tem():
import time
data = time.strftime("%Y%m%d")
return data
def if_exists(pat):
if os.path.exists(pat):
return 0
else:
return 1
def zipFile(files, zip_file):
import zipfile
zp = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
zp.write(files)
zp.close()
def root():
pat = "/var/log/nginx"
patt1 = patt()
os.chdir(pat)
if if_exists(patt1[1]) == 1:
zipFile('%s/%s' % (pat, patt1[0]), '%s/%s' % (pat, patt1[1]))
# os.system("zip %s %s" % (patt1[1], patt1[0]))
os.remove(patt1[0])
os.system("/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true")
os.chown(patt1[0], 995, 993)
os.chown(patt1[1], 995, 993)
remove(pat)
if __name__ == '__main__':
root()
然后写入定时计划任务,每天23:58执行脚本
vim /etc/crontab
58 23 * * * root /usr/bin/python3 /tem/nginx_log.py
写的不好,还请各位多多指定
发表评论
共 0 条评论
暂无评论