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:

  1. 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.
  2. 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 the ps command is being passed as the input to the next command in the line.
  3. The egrep Command: The next command in the line is egrep, which is a variation of the grep command. Grep is a tool used to search for patterns in files, and egrep is an extended version of it that supports regular expressions. The -v option is used to invert the match. So, the egrep command in this line is searching for all processes that do not contain the specified strings, “someApplication” or “someCommand”.
  4. The awk Command: The next command in the line is awk, which is a programming language used for text processing and data extraction. In this line, the awk 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.
  5. The xargs Command: The final command in the line is xargs, 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. The xargs command is being used to execute the kill command for each process ID, which is passed as the input. The kill 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!

This post is also available in: Greek

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.