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 ailbox':'Mailbox not found',
'said\: 550 Domain frequency limited':'Domainfrequenc limited',
'said\: 55':'junk mail',
'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',
'ser unknown':'user unknown'}
for line in log:
m = re.search(mailid,line)
if m is not None:
mailre = re.compile(r'[^\._-][\w\.-]+@(?:+\.)++')
timere = re.compile(r'^\w+\s+\d+\s\d{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('<')
forkey in sdict:
statre = re.search(key,line)
if statre is not None:
status = sdict
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,e.args)
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)
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)</pre>WEB 展现通过apahce+php:<pre class="brush:php;toolbar:false"><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 " ";
$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'value='<?php echo $_POST['st'];?>' class='text' style='width:85px;'/>
-<input type='text' id='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!! 附件有!!最终效果图!!
页:
[1]