【发布时间】: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