Search This Blog

Tuesday 8 December 2009

Script for killing a process owned by root using sudo as localuser

This is the script for giving permission for a local user to kill a proces (here its java) owned by root user.
Ther process to kill, the following conditions should be matched
1. it should be a java process
2. There should be only single process with this id
3. it should be owned by root
4. The user should run it as using sudo.
#!/usr/bin/bash
#Script for killing java proces which is failed to stop by jboss shutdow script.
#Written by latheefp@gmail.com
#echo "The process ID is $1"
#echo "Press return to continue"
read
if [ ! $1 ];
then
echo "Process ID is Empty"
echo "Syntax Error. Usage: $0 "
exit
fi
#This must to be run as root
export ID=`/usr/ucb/whoami`
if [ "$ID" != "root" ]
then
echo '';
echo "You must use sudo to run this program";
echo "Syntax Error. Usage: sudo $0 "
echo '';
exit
fi
PID=$1
#Making sure, its a number
case $PID in
*[!0-9]*) echo "The process ID should be a number";
echo "Syntax Error. Usage: $0 "
exit
esac
#making sure its java, owned by root
if [ `ps -ef|grep $PID|grep -v grep|grep java|grep root|wc -l` -eq 1 ]
then
ps -ef|grep $PID|grep -v grep|grep -v $0
echo " "
echo -n "Do you want to kill this proces: (y/n):"
read answer
if [ "$answer" == "y" ] #condition for checking the user input
then
echo "Killing the process"
kill -9 $PID
if [ `ps -ef|grep $PID|grep -v grep|grep java|grep root|wc -l` -eq 1 ] #Checking process is relly killed or not
then
echo "Unable to kill the process $PID, Please contact System Admin for support"; fi
else
echo "Exiting without killing"
fi
else
echo "Please check the PID, Try with single PID"
echo "Syntax Error. Usage: $0 "
exit
fi

No comments:

Post a Comment