实验环境: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
检查报告
报告综述
开始时间 : {{start_time}} 结束时间 : {{stop_time}}
检测结果 : *** 其它信息:***
问题服务器详细信息
ilo ip
检测结果
登陆
{% for item in body %}
{{ item.ip }}
{{ item.result }}
点击登陆
{% endfor%}
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 = '[email protected]' # 发送用户名
receiver = '[email protected]' # 接收方
#tolist = ['[email protected]','[email protected]'] # 发送给多个人
subject = '服务器健康检查' # 主题
smtpserver = 'email.com' # 服务器地址
username = '[email protected]' # 登陆名,必须与发送用户名相同,否则会报错
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