欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

基于Python脚本实现邮件报警功能

时间:2021-03-31 09:14:53|栏目:Python代码|点击:

使用了smtplib等第三方库,进行发送邮件,完成邮件报警功能

如下是实例 :

#!/usr/bin/python
 
import glob
import operator
from optparse import OptionParser
import smtplib
import email.MIMEText as MIMEText
import email.Utils.formadate as formatdate
 
msg = ""
#主方法
def main():
  global options
  global msg
 
  parser = OptionParser(add_help_option=False)
  parser.add_option("-m", "--mail", dest="mail", type="str", help="email address to send report result (comma separated)")
  parser.add_option("-t", "--title", dest="title", type="str", help="email title (default:Error File Count)")
  parser.add_option("-a", "--admin", dest="admin", type="str", help="set sender address. works with -m option")
  (options, args) = parser.parse_args()
 
  #这里监控文件夹下的文件数,超出25个文件即报警
  datanum = cntFiles("/data/","csv")
  if (operator.gt(datanum,25)):
    msg += " Please be alert : \n the number of files under /data/ path is greater than 25 :"
    msg += "\n =========================================="
    msg += "\n The number of files is : " + str(datanum)
    sendmsg(options,msg)
  print("==== end ====")
 
#添加发送邮件的信息
def sendmsg(options,msg):
  if options.mail:
    toAddr = options.mail
    if options.admin:
      fromAddr = options.admin
    else:
      fromAddr = 'zhangsan@neiyou.cn'#这里是公司的公用SMTP邮箱账号
 
    if options.title:
      subject = options.title
    else:
      subject = 'File Stacking Alarm'
    msg += "\n ========================================== \n"
    print( msg)
    msg = createMsg(fromAddr, toAddr, subject, msg)
    print( msg)
    send(fromAddr, toAddr, msg)
  else:
    print( msg)
 
#glob方法,统计文件夹下的文件数
def cntFiles(in_directory, ext):
  stage = len(glob.glob1(in_directory,"*." + ext))
  return stage
 
#创建邮件头
def createMsg(fromAddr, toAddr, subject, body):
  msg = MIMEText(body)
  msg['Subject'] = subject
  msg['To'] = toAddr
  msg['From'] = fromAddr
  msg['Date'] = formatdate()
  return msg
 
#发送邮件
def send(fromAddr, toAddr, msg):
  try:
    #这里添加公司的SMTP邮箱地址
     s = smtplib.SMTP('192.168.12.120')
     s.sendmail(fromAddr, toAddr.split(','), msg.as_string())
     s.close()
     print("SUCCESS: sending email")
  except smtplib.SMTPException:
     print("ERROR: sending email")
 
if __name__ == '__main__':
  main()

linux上做计划任务,把指令添加进计划任务中:

Errymsfileemail.py -m zhangsan@gongsi.cn -t "[ERROR/$HOST] File Stacking Alarm"

上一篇:使用python分析git log日志示例

栏    目:Python代码

下一篇:Python基于内置函数type创建新类型

本文标题:基于Python脚本实现邮件报警功能

本文地址:http://www.codeinn.net/misctech/91918.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有