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()
Linux使用crontab定时执行Python脚本清理日志的更多相关文章
- Linux系统crontab定时调度Python脚本
Linux系统crontab定时调度Python脚本 一.Python脚本随Linux开机自动运行 #Python脚本:/home/edgar/auto.py #用root权限编辑以下文件:/etc/ ...
- 如何使用Linux的Crontab定时执行PHP脚本的方法[转载]
首先说说cron,它是一个linux下的定时执行工具.根用户以外的用户可以使用 crontab 工具来配置 cron 任务.所有用户定义的 crontab 都被保存在/var/spool/cron 目 ...
- 如何使用Linux的Crontab定时执行PHP脚本的方法
我们的PHP程序有时候需要定时执行,我们可以使用ignore_user_abort函数或是在页面放置js让用户帮我们实现.但这两种方法都不太可靠,不稳定.我们可以借助Linux的Crontab工具来稳 ...
- 使用Linux的Crontab定时执行PHP脚本
0 */6 * * * /home/kdb/php/bin/php /home/kdb/apache/htdocs/lklkdbplatform/kdb_release/Crontab/index.p ...
- linux下crontab定时执行本地脚本和定时访问指定url
https://my.oschina.net/u/2487410/blog/683308 使用linux curl命令讲解:http://www.linuxdiyf.com/linux/2800.ht ...
- linux下crontab定时执行shell脚本调用oracle 存储过程
问题:脚本内调用存储过程,脚本直接执行没问题,使用crontab 执行脚本存储过程未执行 原因:缺少oracle环境变量 解决:在shell脚本里添加oracle的环境变量 #!/bin/sh PAT ...
- crontab 定时执行python脚本
每天8点30分运行命令/tmp/run.sh * * * /tmp/run.sh 每两小时运行命令/tmp/run.sh */ * * * /tmp/run.sh
- mac上使用crontab周期性执行python脚本
这个月买了本书<Linux系统命令及Shell脚本实践指南>, 看到了一个周期性执行任务cron.顿时产生一个想法: mac上有这种机制么? 加上自己也在15年下半年也学了点python脚 ...
- CentOS 7定时执行python脚本
CentOS 7定时执行python脚本 在CentOS下,可以使用crontab进行定时任务的处理. 一.crontab的安装 默认情况下,CentOS 7中已经安装有crontab,如果没有安装, ...
随机推荐
- css 布局,过渡
做了一个小案例,关于我们内边距的处理的,然后再加上一些过渡效果 效果: 具体实现重点加上这里: 具体代码实现: CSS部分: <style> #container{ border:2px ...
- NX二次开发-UFUN文件选择对话框UF_UI_create_filebox
NX11+VS2013 #include <uf.h> #include <uf_ui.h> UF_initialize(); //文件选择对话框 char sPromptSt ...
- NX二次开发-UFUN建模创建特征组UF_MODL_create_set_of_feature
NX11+VS2013 #include <uf.h> #include <uf_modl.h> UF_initialize(); //创建块 UF_FEATURE_SIGN ...
- dajian
http://blog.csdn.net/inject2006/article/details/3064399 http://bbs.dospy.com/thread-16173173-1-464-1 ...
- error C2443: operand size conflict
#include <stdio.h> void main() { int a=98; __asm { mov al,a and al,11011111B mov a ...
- 8、collection
collection 可以理解为一个容器 组织业务逻辑 导入导出 监控或者mock server 实例: 1.新建一个collection,命名为v2ex 2.保存1个请求到v2ex 3.选中v2ex ...
- adb shell 查看内存信息
1.根据包名来查看指定的APP指定数据adb shell "top | grep com.xxx.xxx" 由于这样打印出来的数据没有参数名,可以参考这个命令来看:adb shel ...
- sklearn中pipeline的用法和FeatureUnion
一.pipeline的用法 pipeline可以用于把多个estimators级联成一个estimator,这么 做的原因是考虑了数据处理过程中一系列前后相继的固定流程,比如feature selec ...
- 字符串KMP算法
讲解:http://blog.csdn.net/starstar1992/article/details/54913261 #include <bits/stdc++.h> using n ...
- PAT L2-021. 点赞狂魔 /// sort+unique去重
https://www.patest.cn/contests/gplt/L2-021 题目大意: 微博上有个“点赞”功能,你可以为你喜欢的博文点个赞表示支持.每篇博文都有一些刻画其特性的标签,而你点赞 ...