import elasticsearch
import datetime
import smtplib
from email.message import EmailMessage


if __name__ == '__main__': 
    hosts = '192.168.17.11'
    port = 80
    user = 'zhouyujiang'
    passwd = '8tM9JDN2LVxM'
    http_auth = (user, passwd)
    es = elasticsearch.Elasticsearch(hosts=hosts, port=port, http_auth=http_auth)
    
    send_email_status = ['yellow', 'red']
    
    status_dict  = es.cat.health(format='json')
    
    email_group=['hanye@csm.com.cn','litao@csm.com.cn','zhouyujiang@csm.com.cn',
                 'gengdi@csm.com.cn']
        
    csm_mail_service = 'mail.csm.com.cn'
    sender = 'zhouyujiang@csm.com.cn'
    
    
    if status_dict[0]['status'] in send_email_status:
            date_str = str(datetime.datetime.now())[0:10]
    
            email_subj = '[CCR-ES集群{status}预警] {date}'.format(date=date_str,
                                                             status=status_dict[0]['status'])
            email_msg_body = 'CCR-ES集群{status}预警\ncat_health：\n{status_dict}'.format(status_dict=status_dict[0],
                                                                                            status=status_dict[0]['status'])
            email_msg = EmailMessage()
            email_msg.set_content(email_msg_body)
            email_msg['Subject'] = email_subj
            email_msg['From'] = sender
            email_msg['to'] = email_group
    
            server = smtplib.SMTP(host=csm_mail_service)
            server.send_message(email_msg)
            server.quit()
    else:
        print('ok')
    
    