【问题标题】:Python script that monitors systemctl status of services and sends email via sendmail if it returns false监控 systemctl 服务状态并在返回 false 时通过 sendmail 发送电子邮件的 Python 脚本
【发布时间】:2020-06-12 03:41:10
【问题描述】:

这里有点小白。

我正在尝试编写一个 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)

【问题讨论】:

  • 嗨@Mike,欢迎来到StackOveflow!你有什么问题?

标签: python sendmail monitor systemctl


【解决方案1】:

我会这样做:

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)

【讨论】:

  • 谢谢@Pedro!我试过了,但输出有一些问题。看起来无论我放什么,它都在输出失败消息。此外,在变量上提取的 {service} 部分没有被提取,它实际上只是在您看到它时打印消息“服务 {service} 已关闭,发送电子邮件...”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-06
相关资源
最近更新 更多