花了差不多一周的时候,把python学习了一下,昨天把一直以来非常想重写的nginx日志监控脚本用python重写了一下。重构的原因是原来的shell脚本,是30秒一执行,这样效率太低,并且有重复执行的可能,现在使用守护进程,一秒为一周期,并且可以避免重复执行。
先看代码:
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 |
#!/usr/bin/python2.6 #coding=utf-8 import os import time #日志记录 num_file = '/data/www/www.521php.com/log/num' log_file = '/data/www/www.521php.com/log/www.521php.com.log' #ip屏蔽函数 def shellcmd(ip,con): os.system('/root/shell/nginx/editblocksip.sh add '+ip) os.system('echo '+con+' | mail -s "log info" zhangcunchao_cn@163.com') nowfile = os.getcwd()+"/"+__file__ stime = os.stat(nowfile).st_mtime #修改时间变化退出 while stime == os.stat(nowfile).st_mtime: log_num = str(int(os.popen("cat "+num_file).read())) real_num = str(int(os.popen("cat "+log_file+" | wc -l").read())) if log_num != real_num: #插入新记录条数 os.system('echo '+real_num+' > '+num_file) content = os.popen("tail -n +"+log_num+" "+log_file).read().split("\n") for con in content: if ""!=con: c = con.split(' ') if '403' != c[8] and '112.253.28.43' != c[0]: if ".rar" in c[6]: shellcmd(c[0],con) elif '/wp-comments-post.php' in c[6] and 'MSIE' == c[13] and '6.0;'== c[14]: shellcmd(c[0],con) elif '"-"' == c[11] and '"-"' == c[12] and '.php' in c[6]: shellcmd(c[0],con) time.sleep(1) |
功能我为了简便,使用了shell命令,editblocksip.sh脚本以前说过,就是操作nginx黑名单用的,此脚本还是受到了写php守护进程的启发,1、每次while循环,判断文件自身是否被修改,如果修改就结束,然后由进程守护shell再启用,2、中间的实现也非常简单,记录最近读取的行号,有新记录产生,就执行监控操作,3、过滤已屏蔽的403状态和自身ip地址,4、然后就是自己需要的一些屏蔽规则,有触发则调用editblocksip.sh,将此ip加入403黑名单,这样用户访问会显示我的403页面。
check_python.sh python进程守护队列代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
#!/bin/bash EMAIL='zhangcunchao_cn@163.com' start() { c=`ps w -C python|grep $1|wc -l` if [ $c -lt 1 ] then if [ -f "$1" ];then /usr/bin/python $1 > /dev/null & else `echo 'no such file '$1 | mail -s 'process check error' $EMAIL` fi fi } BASE_PATH=`dirname $0`"/" cd $BASE_PATH start log.py |
原理还是挺简单的,这里我也简单说一下我学习python后对于其感触。
总的来说,python语法上面和php的确有很大区别,其语法其实和js有很大的类似。python最大的特点就是他严格的缩进,他使用缩进来控制代码块,因为其没有{}这样的大括号,变量也和php一样使用了简单的引用计数来做优化,不过其import这样的导入方式其实效率不高,原因大家应该可以理解,我学习过程中还专门做了php和python的执行效率对比,while循环的话php应该比python快一半左右,当然这也不能说明什么,不过python的确是运维工作非常好的助手。
程序本天成,妙手偶得之!我们只是代码的搬运工!
转载请注明:http://www.521php.com/archives/1879/