当etcd集群关闭或不正常时从Python发送电子邮件

2024-06-02 19:19:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在进行etcd集群监控,如果集群关闭,我必须发送电子邮件。当集群运行正常并且我在代码中使用sendmail()函数时,它可以正常工作,但是当集群关闭/运行不正常或者我终止了进程时,它会说:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=2379): Max retries exceeded with url: /health (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x1f6de50>: Failed to establish a new connection: [Errno 111] Connection refused',))

我试着用状态码请求.异常所以它到达了我的代码,但不能这样做。下面是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from subprocess import Popen, PIPE

def getClusterHealth():
    response = requests.get('http://localhost:2379/health')
    data = response.json()

    if response.status_code == 111:
        sendEmail() 

    elif data['health']=="true":
        print("Cluster is healthy")

    else:
        print ("Cluster is not healthy")
        sendEmail()

def sendEmail():
    msg = MIMEText("etcd Cluster Down Sample Mail")
    sender = "example@server.com"
    recipients = ["example1@server.com,example2@servr.com"]
    msg["Subject"] = "etcd Cluster Monitoring Test Multiple ID"  
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    s = smtplib.SMTP('localhost')
    s.sendmail(sender,recipients,msg.as_string())
    s.quit()
    #p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE, universal_newlines=True)
    #p.communicate(msg.as_string())  


if __name__ == "__main__":

    if(len(sys.argv) < 2):
        print("Usage : python etcdMonitoring.py [health|metrics|all]")
    elif(sys.argv[1] == "health"):
        getClusterHealth() 

有什么可能的解决办法?你知道吗


Tags: 代码fromimportlocalhostifresponsesys集群
1条回答
网友
1楼 · 发布于 2024-06-02 19:19:32

您可以捕获ConnectionError异常并评估错误消息,然后根据需要发送电子邮件:

def getClusterHealth():
     try:
        response = requests.get('http://localhost:2379/health')
     except ConnectionError as e:
     // You can use the value of e to check for specific error message and trigger the email
       if str(e) == 'Max retries exceeded with url':
         sendEmail() 

        data = response.json()

        if response.status_code == 111:
            sendEmail() 

        elif data['health']=="true":
            print("Cluster is healthy")

        else:
            print ("Cluster is not healthy")
            sendEmail()

相关问题 更多 >