Python 脚本,用于监视服务的 systemctl 状态并在返回 false 时通过 sendmail 发送电子邮件

标签 python sendmail monitor systemctl

这里有点菜鸟。

我正在尝试编写一个 python 脚本,该脚本本质上将使用 systemctl 实用程序查看服务的子状态,然后如果检测到子状态不是“正在运行”,则使用 sendmail 发送电子邮件。

对于这个特定的实例,仅仅显示服务是否处于事件状态是不够的,还需要显示服务是否正在运行。

我有一个一直在使用的脚本,但它最初是在查找 URL 状态,我将其更改为查看各个服务。我希望监控 6 个不同的服务,但如果其中任何一个服务返回除“正在运行”之外的任何内容,请发送电子邮件

下面是我到目前为止的脚本:

#!/usr/bin/python


import time
import os
from email.mime.text import MIMEText
from subprocess import Popen, PIPE

#The url being monitored.
service1 = "tomcat"
#service2 = "hostcontext"
#service3 = "ecs-ec"
#service4 = "ecs-ep"
#service5 = "ariel_proxy_server"
#service6 = "ecs-ec-ingress"


#The contents of the email
msg = MIMEText(service1 + " is not responding.  Please investigate.")
msg["From"] = "sending address"
msg["To"] = "recipient address"
msg["Subject"] = service1 + "is not responding"

#This loops while the script is running.
# It gets the status returned from the urllib call, if it's not 200 it will email the email contents above.
while True:
    status = os.system('systemctl show tomcat -p SubState | sed "s/SubState=//g"')

    if status == 'running':
        #This is what sends the email.  If you don't have sendmail then update this.
        p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE)
        p.communicate(msg.as_string())
    #The number of seconds the loop will pause for before checking again.  I set it to 60.
    time.sleep(60)

最佳答案

我会做这样的事情:

import time, traceback
from subprocess import getoutput
services = ["mariadb", "apache"]

while 1:
    for service in services:
        try:
            status = getoutput(f"systemctl show {service} -p SubState").split("=")[1].lower()
            if status != 'running':
                print(f"Service {service} is down, send email...")
        except:
            pass
            print(traceback.print_exc())
            # log the error if needed
    time.sleep(60)

关于Python 脚本,用于监视服务的 systemctl 状态并在返回 false 时通过 sendmail 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60444875/

相关文章:

batch-file - 用于监视进程 RAM、CPU%、网络数据、线程的批处理文件

python - 如何从Python中的多个键获取值

python - 如何使用 Pykafka 获取主题的最新消息?

java - 无法使用 -Dcom.sun.management.jmxremote.authenticate=true 启动 Tomcat

ssl - 使用 xampp 为 sendmail 功能启用 SSL 证书

python - 无法使用 python 发送具有多个附件和多个收件人的邮件 [to,cc,bcc]

mysql - 自动监控 MySQL 服务器的崩溃表

python - 如何防止 float 不精确影响 numpy.arange?

python - 从 apache 中的 python 脚本关闭计算机

c++ - 使用 unix sendmail 发送电子邮件