gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:40:38 25 4
gpt4 key购买 nike

这里有点菜鸟。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com