python 自动检测 ilo 健康信息,并发送邮件

148 篇文章 2 订阅
9 篇文章 0 订阅

实验环境:python2.7

方案描述:利用 hpilo 进行健康检测,将有问题的服务器信息通过邮件发送到给管理员,email 利用 jinja2 动态生成模块。

1、 利用 jinja2 自动生成模板

模板 templates/email_template.html

注意:如果变量,例如 {{ item.result }} 中有中文,python2 执行的时候会报错,需要修改 {{ item.result }} 为  {{ item.result .decode('utf8') }}

[root@ansible002 pyscripts]# cat templates/email_template.html
<meta http-equiv="Content-Type"content="text/html;charset=utf-8">
<html align='left'>
<h1>检查报告</h1>
    <body>
    <h2>报告综述</h2>   
    <p>开始时间 : {{start_time}}  结束时间 : {{stop_time}}</p>
    <p>检测结果 : ***  其它信息:***</p>
    <h2>问题服务器详细信息</h2>  
    <table border="1" width = "60%" cellspacing='0' cellpadding='0' align='left'>
    <tr>        
        <th>ilo ip</th>
        <th>检测结果</th>
        <th>登陆</th>
    </tr>
 
    {% for item in body %}
    <tr align='center'>
        <td>{{ item.ip }}</td>
        <td>{{ item.result }}</td>
        <td><a href={{ item.url }}>点击登陆</a></td>
    </tr>
    {% endfor%}
    </table>
    </body>
</html>

2、生成模板 email_html.py

#!/usr/bin/python
#-*- coding:utf8 -*-
from jinja2 import Environment, FileSystemLoader 
 
def generate_html( body, starttime, stoptime):
  env = Environment(loader=FileSystemLoader('templates'))
  template = env.get_template('email_template.html')     
  with open("email.html",'w+') as fout:   
    html_content = template.render(start_time=starttime,stop_time=stoptime,body=body)
    fout.write(html_content.encode('utf-8'))
 
if __name__ == "__main__":
    body = []
    result = {'ip':"10.2.3.3", 'time':"2019", 'resutl':"ok", 'url':"https://10.2.3.3"}
    body.append(result)            
    generate_html(body, 2019, 2019)

2、发邮件 alert_email.py

#!/usr/bin/python
#-*- coding:utf8 -*-
# 文件不能命名为 email.py, 否则会与 from email.mime.text import MIMEText 冲突,报错
import smtplib
from email.mime.text import MIMEText
from email.header import Header

def mail_send(mail_body):
  sender = 'exaple@email.com'   # 发送用户名
  receiver = 'rec1@email.com'   # 接收方
  #tolist = ['rec2@email.com','rec2@email.com']  # 发送给多个人
  subject = '服务器健康检查'   # 主题
  smtpserver = 'email.com'    # 服务器地址
  username = 'exaple@email.com'   # 登陆名,必须与发送用户名相同,否则会报错
  password = '123456'    # 授权码
  
  # 发送的消息 注意第二项必须为plain才能显示,如果为text,发送内容将会以二进制作为附件发送给对方。
  # 如果是想要带有格式,可以采用html格式,第二项可以配置为'html',汉字发送,第三项需要设置为'utf-8'
  msg = MIMEText(mail_body, 'html', 'utf-8')
  msg['Subject'] = Header(subject, 'utf-8')   # 消息的主题
  # 消息来源主要是为了让接收方知道是谁发送的邮件,如果没有这项,邮件将会被当作垃圾邮件处理,发送不成功
  msg['From'] = sender
  msg['To'] = receiver   # 作用同'From'
  #msg['To'] = ','.join(tolist)    # 发送给多个人
    
  # 调用smtplib模块进行发送,这块没啥坑
  smtp = smtplib.SMTP()
  smtp.connect(smtpserver)
  smtp.login(username, password)
  smtp.sendmail(sender, receiver, msg.as_string())
  smtp.quit()

3、ilo 文件内容 devops_machine,10.2.3.3   admin  admin 表示 ilo ip 10.2.3.3, 帐号 admin 密码 admin

10.2.3.3   admin  admin
10.2.3.4   admin  admin
10.2.3.5   admin  admin

4、 ilo 健康检测 health_check_email.py

#!/usr/bin/python
#-*- coding:utf8 -*-
import hpilo
import time
import sys
from alert_email import mail_send
from email_html import generate_html

start_time = time.time()
start_time_new = time.strftime("%Y-%m-%d %H:%M",time.localtime(start_time))
ilos = []
#ilo_file = "/woo/ansible_scripts/files/" + sys.argv[1]
ilo_file = "devops_machine"
with open(ilo_file,'r')as f:
  lines = f.readlines()
  for line in lines: 
    line_list = line.strip().split()
    if line_list == []: #过滤空行
      continue
    ilos.append(line_list)

error_ilo_messages = []  # 存放有问题的 ilo 信息   
for kline in ilos:
  host = kline[0]
  user = kline[1]
  password = kline[2]
  ilo = hpilo.Ilo(host,user,password)  # login ilo
  try:
    health_summary = ilo.get_embedded_health()['health_at_a_glance']  # get ilo health information
  except:
    print "Can not access %s"%host
    print "========= Please check ilo %s==========="%host
    error_dic = {}    
    error_access = "ilo " + host + " can not access "
    error_dic["ip"] = host
    error_dic["result"] = error_access
    error_dic["url"] = "https://" + host
    error_ilo_messages.append(error_dic)
    continue

health_status_list = [] 
  for key in health_summary:
    health_status_list.append(health_summary[key]['status'])
    if health_summary[key]['status'] == 'OK':
      continue
    else:
      print "ilo %s %s status is %s"%(host,key,health_summary[key]['status'])
      error_ms = "ilo %s %s status is %s"%(host,key,health_summary[key]['status'])
      error_dic = {}
      error_dic["ip"] = host
      error_dic["result"] = error_ms
      error_dic["url"] = "https://" + host
      error_ilo_messages.append(error_dic)      
    # 如果所有项都 ok,则打印 “ilo is ok”
  if health_status_list == ['OK']*len(health_summary.keys()): 
    print "ilo %s is ok"%host
  else:
    print "========= Please check ilo %s==========="%host
      
stop_time = time.time()
stop_time_new = time.strftime("%Y-%m-%d %H:%M",time.localtime(stop_time))
time_cost = stop_time - start_time
print "cost %ss time"%time_cost

# 把 error_ilo_messages 信息通过邮件发送给 administrators
if error_ilo_messages != []:
  generate_html(error_ilo_messages, start_time_new, stop_time_new)
  #mail_body = '\t\n'.join(error_ilo_messages)
  with open("email.html","rb")as f:
    mail_body = f.read()
  mail_send(mail_body)
  print "I have send error message to the administrators"

执行  python health_check_email.py,检测到问题即会发送消息到 email

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值