Bit of a nooby here.
I am trying to write a python script that will essentially look at the sub-status of a service using the systemctl utility and then send an email using sendmail if it detects that the substatus is NOT "running".
For this particular instance, it is not enough to just display if the service is active, but running as well.
I have a script I have been working with but it was originally looking for URL statuses, and I changed it to look at individual services. I am looking to monitor 6 different services but send an email if any of them return anything except "running"
Below is the script I have so far:
#!/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)