Linux使用crontab定时执行Python脚本清理日志

Linux中,周期执行的任务一般由crond这个守护进程来处理。cron读取一个或多个配置文件,这些配置文件中包含了命令行及其调用时间。crond的配置文件称为“crontab”,是“cron table”的简写。

一、crond服务 -- crontab

查看cron服务状态

[root@VM_138_80_centos Home]# sudo service crond status
crond (pid  29349) is running...

开启cron服务

[root@VM_138_80_centos Home]# sudo service crond start
Starting crond:                                            [  OK  ]

关闭cron服务

[root@VM_138_80_centos Home]# sudo service crond stop
Stopping crond:                                            [  OK  ]

重启cron服务

[root@VM_138_80_centos Home]# sudo service crond restart
Stopping crond:                                            [  OK  ]
Starting crond:                                            [  OK  ]

二、crontab服务用法

  • crontab –e : 修改 crontab 文件,如果文件不存在会自动创建。
  • crontab –l : 显示 crontab 文件。
  • crontab -r : 删除 crontab 文件。
  • crontab -ir : 删除 crontab 文件前提醒用户。

在crontab文件中写入需要执行的命令和时间,该文件中每行都包括六个域,其中前五个域是指定命令被执行的时间,最后一个域是要被执行的命令。每个域之间使用空格或者制表符分隔。

格式如下:

minute hour day-of-month month-of-year day-of-week commands    

合法值为:00-59 00-23 01-31 01-12 0-6 (0 is sunday)

除了数字还有几个特殊的符号:"*"、"/"和"-"、","

  • *代表所有的取值范围内的数字
  • "/"代表每的意思,"/5"表示每5个单位
  • "-"代表从某个数字到某个数字
  • ","分开几个离散的数字

注:commands 注意以下几点

  • 要是存在文件,要写绝对路径
  • 即使是打印也不会显示在显示屏,在后台运行,最好重定向日志

三、实战演练

运行crontab -e命令,在文本中写入

例如:每天早上6点清理前天的日志文件

0 6 * * * 清理日志命令或执行脚本

清理日志命令或执行脚本修改为你想执行的操作,我这里写入"python /root/scripts/time_clear_ireader_logs.py"

然后进行保存退出,使用crontab -l 进行查看定时任务,看下面的第三条。

[root@VM_138_80_centos Home]# crontab -l
*/1 * * * * /usr/local/qcloud/stargate/admin/start.sh > /dev/null 2>&1 &
*/20 * * * * /usr/sbin/ntpdate ntpupdate.tencentyun.com >/dev/null &
0 6 * * * "python /root/scripts/time_clear_ireader_logs.py"

四、Python清理脚本

脚本中有配置内容,可按需修改

# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# import math, os, sys, time
import traceback
import subprocess
import datetime

# 定时任务脚本,删除归档日志文件

# 定义前两天的时间
the_day_before_yesterday = (datetime.date.today() + datetime.timedelta(-2)).strftime('%y_%m_%d')

# 定义文件路径
logs_file_Path = {
    "/data/Home/Logs/": "删除用户端归档日志文件[Home]",
    "/data/Admin/Logs/": "删除管理员端归档日志文件[Admin]",
}


# 清除大于1G的文件
def clear_tomcat_archive_logs():
    print("<---删除tomcat归档日志文件--->")
    for file_path, message in logs_file_Path.items():
        linux_command = "rm -rf " + file_path + "*" + the_day_before_yesterday + "*"
        response_message, response_code = execute_shell(linux_command)
        check_result(int(response_code), message)
    print("<---删除tomcat归档日志文件--->")


# 执行linux命令获取返回结果与返回码
def execute_shell(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 check_result(result, message):
    if result == 0:
        print(message + "执行成功")
    else:
        print(message + "执行失败")


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


# 最终执行的方法
def final_execute():
    print("<---The time_clear_ireader_logs.py Begin,the time is [" + datetime.datetime.now().strftime(
        '%Y-%m-%d %H:%M:%S') + "]--->")
    print('\n' * 1)
    try:
        clear_tomcat_archive_logs()
    except Exception as e:
        print_excption(e)

    print('\n' * 1)
    print("<---The time_clear_ireader_logs.py End,the time is [" + datetime.datetime.now().strftime(
        '%Y-%m-%d %H:%M:%S') + "]--->")


if __name__ == '__main__':
    # 最终执行
    final_execute()

猜你喜欢

转载自www.cnblogs.com/osheep/p/11294219.html