python 监控 api 脚本

990阅读 0评论2015-05-30 fathermotherson
分类:Python/Ruby

这个脚本的作用是: 访问 url,返回码大于500就发送报警邮件

主要用了 requests 模块, 所以跑监控脚本的 机器要先安装 requests
pip install requests

点击(此处)折叠或打开

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-

  3. import smtplib
    from email.mime.text import MIMEText
    import sys
  4. import requests


  5. urls=[]
  6. urls.append('')
  7. urls.append('')


  8. # 报警邮件参数设置, 前三行是用来发件的邮箱的配置
  9. mail_host = 'smtp.exmail.qq.com'
  10. mail_user = 'xj@abc.cn' #qq邮箱这个地方必须写全!
  11. mail_pass = "123456"
  12. mail_postfix = 'suibianxie.com'
  13. admin_email = 'admin@youremail.com'




  14. # 邮件发送函数
  15. def send_mail(to_list,subject,content):
  16.     me = mail_user+"<"+mail_user+"@"+mail_postfix+">"
  17.     msg = MIMEText(content)
  18.     msg['Subject'] = subject
  19.     msg['From'] = me
  20.     msg['to'] = to_list


  21.     try:
  22.         s = smtplib.SMTP()
  23.         s.connect(mail_host)
  24.         s.login(mail_user,mail_pass)
  25.         s.sendmail(me,to_list,msg.as_string())
  26.         s.close()
  27.         return True
  28.     except Exception,e:
  29.         print str(e)
  30.         return False


  31. # 主体部分
  32. for url in urls:
  33.     try:
  34.         r = requests.get(url,timeout=3)
  35.         if r.status_code >= 500:
  36.             msg = 'Error: ' + str(r.status_code) + ' ' + url
  37.             print "send email"
  38.             send_mail( admin_email,"api error",msg)
  39.             print "done"
  40.     except requests.exceptions.ConnectionError as e:
  41.         print "These aren't the domains we're looking for."
  42.     except requests.exceptions.ConnectTimeout as e:
  43.         print "Too slow Mojo!"
  44.     except requests.exceptions.HTTPError as e:
  45.         print "And you get an HTTPError:", e.message
 之后放 crontab 里面运行就行

上一篇:Redis Cluster 介绍与使用
下一篇:根分区 quota