User Tools

Site Tools


check_service_and_restart_if_failed

Check service and restart if failed

Check the service if nginx is running and if not start

#!/usr/bin/env bash
 
# Enable System level logging
# Redirect log to logger
exec 1> >(logger -t $(basename $0)) 2>&1
 
STATUS="$(systemctl is-active nginx.service)"
 
if [ "${STATUS}" != "active" ]; then
   echo "Not running starting Service : Nginx"
   systemctl start nginx.service
fi

for python

#!/usr/bin/env python3
import os
import logging
from systemd import journal
 
def main(serviceName):
  status = os.system('systemctl is-active --quiet ' + serviceName)
  finisher(status)
 
def finisher(status):
  if status is not 0:
    status = os.system('systemctl start --quiet ' + serviceName)
    print(status)
    if status is not 0:
      log.error('Failed to start: ' + serviceName)
    else:
      log.info('Started service: ' + serviceName)
 
if __name__ == "__main__":
 
  # Initialize and handle options
  log = logging.getLogger(__file__)
  log.addHandler(journal.JournaldLogHandler())
  log.setLevel(logging.INFO)
 
  # Define service array
  serviceName = ["nginx"]
  for service in serviceName:
    main(service)
check_service_and_restart_if_failed.txt · Last modified: 2020/08/10 02:35 (external edit)