How can I kill process by specific name and exclude root processes
Solution 1
This will generate a list of processes with the given name, and a list of processes with the given name running as root, then run comm
to find processes in the first list that are not in the second list, then kill them.
#!/bin/ksh
if test $# != 1
then
echo usage: "$0" processname
exit 1
fi
pname="$1"
kill $(comm -23 <(pgrep "$pname"|sort -n) <(pgrep -u root "$pname"|sort -n))
Solution 2
I am using SUSE , but assuming it works similar on Solaris.
Kill process for a User
In order to kill a process by its user id You can do following
#pkill -U <username>
Check processes for a User
If you just want to check what processes are running for a particular user before killing his processes, you can use:
pgrep -U <username
Kill process for multiple users
#pkill -U <user1>,<user2>,<user3>
and so on.
Kill all users except root
I know you are avoiding sed , awk , grep. But its easier to write a script rather than having to type each user name. Here is a sample. Please check on sanbox before executing on production.
ps -aef |grep -v UID |grep -v root |awk '{print $1}'
|sort -u |while read name
do
echo "Killing process for user $name"
pkill -U $name
done
Related videos on Youtube
Aviv
Updated on September 18, 2022Comments
-
Aviv over 1 year
Not a long time ago we found out about
pkill
and we had in mind to start using it in a setuid (for root) script for global clean-up of processes. This could save us lots of stupid maintenance where some clients can´t remove general resources using their scripts only due not important permission limitations.However, after some struggling we only came up with
pkill -v -u root <name>
(so far we intent to make it simple and prevent from devolving into a long and ugly script withsed
,awk
,grep
and so on). Of course it doesn´t work — it just kills everything but the processes that match the given name.Is there a any short modified version of that
pkill
command that get us the results we need?P.S: I want to avoid any discussions about the morality of giving some sort of root power to the users.
The running OS is solaris 10, if that matters.
-
Otheus about 8 yearsPlease specify the constraints and aims of which processes you want killed.
-
New Atech about 8 yearsWhich shell do you use?
-
Andrew Henle about 8 yearsAre there any group memberships in common between the users and the process(s) that need to be killed? If so, this might help: serverfault.com/questions/325128/…
-
-
Anil_M about 8 yearsYou can preview the script by replacing
pkill -U $name
withecho "pkill -U $name"
to make sure it works and kills right processes -
Aviv over 2 yearsI remember looking at it 5 years ago and was overwhelemed with the comm command. but now seeing this multiple times, this is a great solution!