Wednesday, June 8, 2016

service-watchdog script for linux server.

#!/bin/bash
# Created by Shailesh Sutar on 6/8/16
#
# Copyright 2016
# service-watchdog.sh - Monitor essential services
# Uncomment line bellow to enable debugging
#set -x

IS_KEY=$1

if [ "x$IS_KEY" == "x" ] ;then
    IS_KEY=false
else
    IS_KEY=true
fi

NGINX=/etc/init.d/nginx
LOGS=/home/user-one/logs/watchdog
LOG=$LOGS/watchdog.log

function log {
    MESSAGE=$1
    TS=$(date)
    echo "$TS - $MESSAGE" >> $LOG
}

function check_webserver {
    pid=$(ps -ef | grep "/usr/sbin/nginx"|grep -v "grep"|awk '{print $2}'|sort -n|uniq|head -1)
    if [ "x$pid" == "x" ]; then
        log "Restarting nginx"
        sudo $NGINX restart
    fi
}

mkdir -p $LOGS

# main

check_webserver

Make sure when you configure this script in crontab, you put argument as true or may be false.
True : to make this script work.
False : to stop this script to work.