python重構日誌監控指令碼的程式碼

來源:互聯網
上載者:User

先看代碼:

nginx日誌監控指令碼Python

#!/usr/bin/python2.6
#coding=utf-8
import os
import time
#日誌記錄
num_file = '/data/www/www.111cn.net/log/num'
log_file = '/data/www/www.111cn.net/log/www.111cn.net.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進程守護隊列代碼

Shell


#!/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的確是營運工作非常好的助手。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.