#Shell Script to check Service Status Check And start If It’s Not Running
#!/bin/bash
if [ "$#" = 0 ] # check if service name passed to script as argument, if there no arguments (0) do next
then
echo “Usage $0 ” #write to terminal usage
exit 1 #since no arguments – we need to exit script and user re-run it
fi
service=$1 #get service name from first argument
is_running=`ps aux | grep -v grep| grep -v “$0″ | grep $service| wc -l | awk ‘{print $1}’` #this check
#if service running using ps command, after we remove our process from output, since script will also
# match, with wc we count number of matching lines .
if [ $is_running != "0" ] ; # is number of lines are not 0 do next
then
echo “Service $service is running” #just put this line to terminal
else #if number of precesses is 0
echo “Service $service is not running” #just put this string to terminal
initd=`ls /etc/init.d/ | grep $service | wc -l | awk ‘{ print $1 }’` #checking for files in /etc/init.d
#(directory with start-up scripts) with name similar to service
if [ $initd = "1" ]; #if there is script with similar name
then
startup=`ls /etc/init.d/ | grep $service` # this line get name of startup script (ls –
# lists files in directory
echo -n “Found startap script /etc/init.d/${startup}. Start it? Y/n ? ” #just put to
#terminal this line
read answer #waiting for user answer
if [ $answer = "y" -o $answer = "Y" ]; #if answer Y or y
then
echo “Starting service…”
/etc/init.d/${startup} start # running startup script
fi #exit of if loop
fi #exit of if loop
fi#exit of if loop
Results
server:~/$ ./service.sh apparmor
Service apparmor is not running
Found startap script /etc/init.d/apparmor. Start it? Y/n ? Y
Starting service…
* Starting AppArmor profiles [OK]
No comments:
Post a Comment
Thank You for your Comments, We will read and response you soon...