Linux using crontab regular implementation of Python script to clean logs

Linux, the task execution cycle is generally handled by the crond daemon. cron read one or more configuration files, the configuration file contains the command line and call time. crond configuration file is called "crontab", it is a "cron table" shorthand.

A, crond service - crontab

View the cron service status

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

Open cron service

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

Close cron service

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

Restart the cron service

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

Two, crontab service usage

  • crontab -e: Modify crontab file, if the file does not exist will be created automatically.
  • crontab -l: Display a crontab file.
  • crontab -r: remove crontab files.
  • crontab -ir: crontab files before deleting alert the user.

Write crontab file commands and the time required to perform the file each line consists of six domains, of which the first five fields is the time specified command is executed, the last field is the command to be executed. Use space or tab-delimited between each field.

Format is as follows:

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

Legal values: 00-59 00-23 01-31 01-12 0-6 (0 is sunday)

In addition to digital as well as several special symbol: "*", "/" and "-", ""

  • * On behalf of all the numbers in the range of
  • "/" Representing each of meaning, "/ 5" means every 5 units
  • "-" represents the numbers from one to a digital
  • "" Several separate discrete digital

Note: commands to note the following

  • If the file exists, write the absolute path
  • Even print will not be shown on the display, runs in the background, it is best to redirect log

Third, the practical exercise

Run crontab -e command, written in the text

For example: 6:00 every morning to clean up the log files the day before yesterday

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

Cleanup log command or script to modify the operation you want to perform, write me here"python /root/scripts/time_clear_ireader_logs.py"

Then save and exit, use the crontab -l to view regular tasks, see Article III below.

[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"

Four, Python script to clean up

There configure script content can be modified as needed

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

Guess you like

Origin www.cnblogs.com/osheep/p/11294219.html