评论

收藏

[JavaScript] python分析postfix邮件日志的状态

开发技术 开发技术 发布于:2021-06-24 09:10 | 阅读数:205 | 评论:0

公司需求:客服通过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+\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('<')
          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)</pre>WEB 展现通过apahce+php:<pre class="brush:php;toolbar:false">&lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8"&gt;
  <?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'  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-&gt;name=="mailid")
    {
    echo "&lt;td&gt;&amp;nbsp;"."邮件ID"."&amp;nbsp;&lt;/td&gt;";  }
    if ($field-&gt;name=="sendtime")
    {
    echo "&lt;td&gt;&amp;nbsp;"."发送时间"."&amp;nbsp;&lt;/td&gt;";  }
    if ($field-&gt;name=="fromaddress")
    {
    echo "&lt;td&gt;&amp;nbsp;"."邮件发送者"."&amp;nbsp;&lt;/td&gt;";  }
    if ($field-&gt;name=="toaddress")
    {
    echo "&lt;td&gt;&amp;nbsp;"."邮件接收者"."&amp;nbsp;&lt;/td&gt;";  }
    if ($field-&gt;name=="status")
    {
    echo "&lt;td&gt;&amp;nbsp;"."邮件发送结果"."&amp;nbsp;&lt;/td&gt;";  }
  }
  echo "</tr>";
  if(isset($_POST['submit']) && $_POST['submit'])
{  $flag = 0;
  //按查询条件输出结果
while($rows = mysql_fetch_row($resultq))
    {//使用while遍历所有记录,并显示在表格的tr中
        echo "&lt;tr bgcolor=#CC9999&gt;";
        for($i = 0; $i &lt; count($rows); $i++)
        echo "&lt;td&gt;&amp;nbsp;".$rows[$i]."&lt;/td&gt;";
       $flag++;
    }
    echo "&lt;/tr&gt;&lt;/table&gt;";
    if ($flag == 0)
    echo "&lt;table align=center bgcolor=#cc3366 &gt;没有找到合适的记录&lt;/table&gt;";
}  else
{  //默认输出结果
while($rows = mysql_fetch_row($result)){
    //使用while遍历所有记录,并显示在表格的tr中  
        echo "&lt;tr bgcolor=#CC9999&gt;";
        for($i = 0; $i &lt; count($rows); $i++)
        echo "&lt;td&gt;&amp;nbsp;".$rows[$i]."&lt;/td&gt;";
    }
    echo "&lt;/tr&gt;&lt;/table&gt;";
  }
?>showdate.js 时间那个 通用的JS!! 附件有!!最终效果图!! DSC0000.jpg
关注下面的标签,发现更多相似文章