栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python分析postfix邮件日志的状态

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python分析postfix邮件日志的状态


公司需求:客服通过WEB想查询 某一时间他发送的邮件的 状态,如果是拒绝是什么原因导致的。

#!/usr/bin/env python

# -*- coding: utf-8 -*-

import re

import threading

import MySQLdb

import datetime,time

###########################################################################################

def Gainid(log):

    #mail id re

    mailid = re.compile(r'w{11}:')

    list_id = []

    for line in log:

        m  = mailid.search(line)

        if m is not None:

            list_id.append(m.group().strip(':'))

        else:

            continue

    return list(set(list_id))

def HandleLog(log,mailid):

    tomail = ''

    fmail = ''

    status = 'other'

    sdict={'status=sent':'ok',

'Sender address rejected':'Sender address rejected',

'Recipient address rejected':'Recipient address rejected',

'said: 550 [Mm]ailbox':'Mailbox not found',

'said: 550 Domain frequency limited':'Domainfrequenc limited',

'said: 55[3-4]':'junk mail',

'[uU]ser not exist':'user not exist',

'said: 550 User suspended':'User suspended',

'said: 550 User not found':'User not found',

'Message rejected as spam by Content Filterin':'Message rejected as spam by Content Filterin',

'said: 550 No such user':'user not exist',

'[Uu]ser unknown':'user unknown'}

    for line in log:

        m = re.search(mailid,line)

        if m is not None:

            mailre = re.compile(r'[^._-][w.-]+@(?:[A-Za-z0-9]+.)+[A-Za-z]+')

            timere = re.compile(r'^w+s+d+sd{2}:d{2}:d{2}')

            nt = timere.search(line)

            mtime = nt.group()

            n = mailre.search(line)

            if n is not None:

                f = re.search(r'from=',line)

                t = re.search(r'to=',line)

                if f is not None:

                    fmail = n.group().strip('<')

                if t is not None:

                    tmail = n.group().strip('<')

                    for  key in sdict:

                        statre = re.search(key,line)

                        if statre is not None:

                            status = sdict [key]

                        else:

                            pass

                    print ("id: %s date :%s  |frdr: %s |  todr: %s | status: %s" % (mailid,mtime ,fmail,tmail,status))

                    ttime = fromttime(mtime)    

                    sql = "insert into mailtest values('%s','%s','%s','%s','%s')" % (mailid,ttime ,fmail,tmail,status)            

                    insertmail(sql)

#                    if tomail:

#                        tomail = tomail+"(%s|%s)" % (tmail,status)

#                    else:

#                        tomail = "(%s|%s)" % (tmail,status)

        else:

            continue

def fromttime(mtime):

    today = datetime.date.today()

    

    yer   =     today.strftime("%Y")      

    mtime =  yer + mtime

    ntime =  time.strptime(mtime,"%Y%b  %d %H:%M:%S")

    ttime =  time.strftime('%Y-%m-%d %H:%M:%S',ntime)

    return ttime

def insertmail(sql):

    try:

        conn=MySQLdb.connect(host='localhost',user='root',passwd='',port=3306,db='mailawst')

        cur = conn.cursor()

    cur.execute(sql)

        cur.close()

    conn.commit()

        conn.close()

    except MySQLdb.Error,e:

        print "Mysql Error %d: %s" % (e.args[0],e.args[1])

         

        

def main(logfile):

    #open file

    f = open(logfile,'r')

    log = f.readlines()

    f.close()

    #mail id 

    mailid = Gainid(log)

    #HandleLog

    for i in range(len(mailid)):

        HandleLog(log,mailid[i])        

#    HandleLog(log,'850DA916966')        

if __name__ == "__main__":

    today = datetime.date.today() 

    oneday = datetime.timedelta(days=1)

#    d1 = datetime.datetime.now()

#    d3 = d1 + datetime.timedelta(hours=10)

#    d3.ctime()   

    yesterday = today - oneday

    tommorrow = today + oneday

    #print yesterday 

    zhi = yesterday.strftime("%Y%m%d")

    logfile = "/data/maillog/mail.log.%s" % zhi

        #logfile = "/data/maillog/mail.log.20140516"

    main(logfile)

WEB 展现通过apahce+php:

error_reporting(E_ALL & ~E_NOTICE);

$mysql_server_name='localhost';

$mysql_username='root';

$mysql_password='admin';

$mysql_database='mailawst';

$conn=mysql_connect($mysql_server_name,$mysql_username,$mysql_password,$mysql_database);

$sql='select * from mailtest where sendtime>curdate()-1 limit 5';

//mysql_query($sql);    

mysql_select_db($mysql_database,$conn);

$result=mysql_query($sql,$conn);

$resultq=mysql_query($query,$conn);

//mysql_close($conn);   

echo "

"."邮件发送状态查询"."
" ;

echo " ";

$acceptmail = trim($_POST['acceptmail']);

$st = $_POST['st'];

$et = $_POST['et'];

$query = 'select * from mailtest where sendtime >='.'''.$st.'''.' and Date(sendtime)<='.'''.$et.'''.' and toaddress='.'''.$acceptmail.''';

$resultq=mysql_query($query,$conn);

//echo $query." ";

//echo $acceptmail.$st.$et;

//查询条件

echo "";

?>


echo "

";

while($field = mysql_fetch_field($result)){//使用while输出表头

        if ($field->name=="mailid")

        {

        echo "

";  }

        if ($field->name=="sendtime")

        {

        echo "

";  }

        if ($field->name=="fromaddress")

        {

        echo "

";  }

        if ($field->name=="toaddress")

        {

        echo "

";  }

        if ($field->name=="status")

        {

        echo "

";  }

 }

echo "

";

if(isset($_POST['submit']) && $_POST['submit'])

{

  $flag = 0;

//按查询条件输出结果

        while($rows = mysql_fetch_row($resultq))

        {//使用while遍历所有记录,并显示在表格的tr中

                echo "

";

                for($i = 0; $i < count($rows); $i++)

                echo "

";

             $flag++;

        }

        echo "

 "."邮件ID"."  "."发送时间"."  "."邮件发送者"."  "."邮件接收者"."  "."邮件发送结果"." 
 ".$rows[$i]."
";

        if ($flag == 0)

        echo "

没有找到合适的记录
";

}

else

{

//默认输出结果

        while($rows = mysql_fetch_row($result)){

        //使用while遍历所有记录,并显示在表格的tr中  

                echo "";

                for($i = 0; $i < count($rows); $i++)

                echo " ".$rows[$i]."";

        }

        echo "";

}

?>

showdate.js 时间那个 通用的JS!! 附件有!!

最终效果图!!

wKiom1SFOF6BnewqAAGclcYWgH8950.jpg

©著作权归作者所有:来自51CTO博客作者houzaicunsky的原创作品,谢绝转载,否则将追究法律责任


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/221067.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号