python分析postfix邮件日志的状态

本文涉及的产品
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
日志服务 SLS,月写入数据量 50GB 1个月
简介:

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



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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
#!/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  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:
         =  re.search(mailid,line)
         if  is  not  None :
             mailre  =  re. compile (r '[^\._-][\w\.-]+@(?:[A-Za-z0-9]+\.)+[A-Za-z]+' )
             timere  =  re. compile (r '^\w+\s+\d+\s\d{2}\:\d{2}:\d{2}' )
             nt  =  timere.search(line)
             mtime  =  nt.group()
             =  mailre.search(line)
             if  is  not  None :
                 =  re.search(r 'from\=' ,line)
                 =  re.search(r 'to\=' ,line)
                 if  is  not  None :
                     fmail  =  n.group().strip( '<' )
                 if  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
     =  open (logfile, 'r' )
     log  =  f.readlines()
     f.close()
 
     #mail id 
     mailid  =  Gainid(log)
     #HandleLog
     for  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:

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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<meta http-equiv= "Content-Type"  content= "text/html; charset=UTF-8" >
<?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  "<table align=center><tr><td><font size=6>" . "邮件发送状态查询" . "</front></td></tr></table>"  ;
echo  "&nbsp" ;
$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  "<script type='text/javascript' src='./showdate.js'></script>" ;
?>
<form action= "<?php echo $_SERVER['PHP_SELF'];?>"  method= "post" >
<table align=center>
<tr><td>接收者邮件地址:<input type= 'text'  value= '<?php echo $_POST[' acceptmail '];?>' name= 'acceptmail'  style= 'width:180;'  /></td></tr>
<tr><td>邮件发送时间段:<input type= 'text'  id= 'st'  name= 'st'  onclick= "return Calendar('st');"  value= '<?php echo $_POST[' st '];?>'  class = 'text'  style= 'width:85px;' />
-<input type= 'text'  id= 'et'  onclick= "return Calendar('et');"  value= '<?php echo $_POST[' et '];?>'  name= 'et'  class = 'text'  style= 'width:85px;' />
  <input type= "submit"  name= "submit"  value= "查询"  style= 'width:50px;' >
  </td></tr>
</table></form>
<br>
<table align=center>
<?php
echo  "<tr>" ;
while ( $field  = mysql_fetch_field( $result )){ //使用while输出表头
         if  ( $field ->name== "mailid" )
         {
         echo  "<td>&nbsp;" . "邮件ID" . "&nbsp;</td>" ;  }
         if  ( $field ->name== "sendtime" )
         {
         echo  "<td>&nbsp;" . "发送时间" . "&nbsp;</td>" ;  }
         if  ( $field ->name== "fromaddress" )
         {
         echo  "<td>&nbsp;" . "邮件发送者" . "&nbsp;</td>" ;  }
         if  ( $field ->name== "toaddress" )
         {
         echo  "<td>&nbsp;" . "邮件接收者" . "&nbsp;</td>" ;  }
         if  ( $field ->name== "status" )
         {
         echo  "<td>&nbsp;" . "邮件发送结果" . "&nbsp;</td>" ;  }
  }
echo  "</tr>" ;
if (isset( $_POST [ 'submit' ]) &&  $_POST [ 'submit' ])
{
   $flag  = 0;
//按查询条件输出结果
         while ( $rows  = mysql_fetch_row( $resultq ))
         { //使用while遍历所有记录,并显示在表格的tr中
                 echo  "<tr bgcolor=#CC9999>" ;
                 for ( $i  = 0;  $i  count ( $rows );  $i ++)
                 echo  "<td>&nbsp;" . $rows [ $i ]. "</td>" ;
              $flag ++;
         }
         echo  "</tr></table>" ;
         if  ( $flag  == 0)
         echo  "<table align=center bgcolor=#cc3366 >没有找到合适的记录</table>" ;
}
else
{
//默认输出结果
         while ( $rows  = mysql_fetch_row( $result )){
         //使用while遍历所有记录,并显示在表格的tr中  
                 echo  "<tr bgcolor=#CC9999>" ;
                 for ( $i  = 0;  $i  count ( $rows );  $i ++)
                 echo  "<td>&nbsp;" . $rows [ $i ]. "</td>" ;
         }
         echo  "</tr></table>" ;
}
 
?>

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

最终效果图!!

wKiom1SFOF6BnewqAAGclcYWgH8950.jpg



本文转自 houzaicunsky 51CTO博客,原文链接:http://blog.51cto.com/hzcsky/1417112


相关实践学习
通过日志服务实现云资源OSS的安全审计
本实验介绍如何通过日志服务实现云资源OSS的安全审计。
相关文章
|
26天前
|
JSON 算法 API
深度分析小红书城API接口,用Python脚本实现
小红书作为以UGC内容为核心的生活方式平台,其非官方API主要通过移动端抓包解析获得,涵盖内容推荐、搜索、笔记详情、用户信息和互动操作等功能。本文分析了其接口体系、认证机制及请求规范,并提供基于Python的调用框架,涉及签名生成、登录态管理与数据解析。需注意非官方接口存在稳定性与合规风险,使用时应遵守平台协议及法律法规。
|
27天前
|
JSON API 数据格式
深度分析大麦网API接口,用Python脚本实现
大麦网为国内领先演出票务平台,提供演唱会、话剧、体育赛事等票务服务。本文基于抓包分析其非官方接口,并提供Python调用方案,涵盖演出列表查询、详情获取及城市列表获取。需注意非官方接口存在稳定性风险,使用时应遵守平台规则,控制请求频率,防范封禁与法律风险。适用于个人学习、演出信息监控等场景。
|
25天前
|
数据采集 存储 JSON
地区电影市场分析:用Python爬虫抓取猫眼/灯塔专业版各地区票房
地区电影市场分析:用Python爬虫抓取猫眼/灯塔专业版各地区票房
|
25天前
|
JSON API 开发者
深度分析阿里妈妈API接口,用Python脚本实现
阿里妈妈是阿里巴巴旗下营销平台,提供淘宝联盟、直通车等服务,支持推广位管理、商品查询等API功能。本文详解其API调用方法,重点实现商品推广信息(佣金、优惠券)获取,并提供Python实现方案。
|
24天前
|
数据采集 数据可视化 API
驱动业务决策:基于Python的App用户行为分析与可视化方案
驱动业务决策:基于Python的App用户行为分析与可视化方案
|
24天前
|
API 数据安全/隐私保护 开发者
深度分析苏宁API接口,用Python脚本实现
深度分析苏宁API接口,用Python脚本实现
|
25天前
|
JSON API 数据安全/隐私保护
深度分析虾皮城API接口,用Python脚本实现
虾皮开放平台提供丰富的API接口,支持商品管理、订单处理及促销信息查询等功能。本文详解API认证机制与调用方法,基于Python实现商品价格及到手价获取方案,适用于电商数据分析与运营。
|
26天前
|
数据采集 机器学习/深度学习 数据可视化
Python量化交易:结合爬虫与TA-Lib技术指标分析
Python量化交易:结合爬虫与TA-Lib技术指标分析
|
26天前
|
前端开发 Shell API
深度分析58同城API接口,用Python脚本实现
58同城为国内知名分类信息平台,涵盖房产、招聘、二手车等多领域。本文基于网页抓包与解析,分享其非官方接口的Python实现方案,分析核心接口特性与反爬应对策略,适用于数据学习与信息聚合。注意:非官方接口存在风险,使用需遵守平台规则。
|
26天前
|
并行计算 知识图谱 Python
综合能源系统分析的统一能路理论(三):《稳态与动态潮流计算》(Python代码实现)
综合能源系统分析的统一能路理论(三):《稳态与动态潮流计算》(Python代码实现)

推荐镜像

更多