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

问题描述 投票:1回答:1

这里是一个nooby位。

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

这里的nooby位。我正在尝试编写一个Python脚本,该脚本本质上将使用systemctl实用程序查看服务的子状态,然后在检测到...

python sendmail monitor systemctl
1个回答
0
投票

我会做类似的事情:

© www.soinside.com 2019 - 2024. All rights reserved.