Kill all processes of a user (Or kill almost all using an exception list) in linux
Following is a command a root can use to stop all active threads of a user with an exception list (you can replace someApplication) with specific commands you wish to keep alive.
ps -U useraccount | egrep -v "someApplication|someCommand" | awk '{print $2}' | xargs -t kill;
In this command, the following actions are being taken:
- The
ps
Command: The first command in this line,ps
, is a process status command. It shows the current status of all processes on the system. The-U
option is used to specify the user account. So, in this case, the command will show the status of all processes that are running under the specified user account. - The
|
Operator: The|
symbol, also known as the pipe operator, is used to redirect the output of one command to the input of another command. So, in this case, the output of theps
command is being passed as the input to the next command in the line. - The
egrep
Command: The next command in the line isegrep
, which is a variation of thegrep
command.Grep
is a tool used to search for patterns in files, andegrep
is an extended version of it that supports regular expressions. The-v
option is used to invert the match. So, theegrep
command in this line is searching for all processes that do not contain the specified strings, “someApplication” or “someCommand”. - The
awk
Command: The next command in the line isawk
, which is a programming language used for text processing and data extraction. In this line, theawk
command is being used to extract the second column of the output, which is the process ID. The{print $2}
part of the command specifies that the second column should be printed. - The
xargs
Command: The final command in the line isxargs
, which is used to execute commands based on the input. In this case, the-t
option is used to display the commands that are being executed. Thexargs
command is being used to execute thekill
command for each process ID, which is passed as the input. Thekill
command is used to terminate a process.
In summary, this command is used to find all processes running under the specified user account, excluding the processes that contain the specified strings “someApplication” or “someCommand”. The process IDs are extracted and passed as the input to the ‘kill’ command, which terminates the processes. The ‘-t’ option is used to display the commands being executed by xargs
.
The next example is very similar to the first one but it used to kill all of the processes of your account.
ps x | egrep -v "ssh|screen|ps|bash|awk|tail" | awk '{print $1}' | tail -n +2 | xargs -t kill;
NOTE: USE WITH CAUTION!