In Linux, there are situations where you may need to forcibly log out a user. This can be necessary when performing system maintenance, addressing unauthorized access, or managing hung user sessions. The ability to forcefully end a session ensures you can maintain control over the system without requiring a full reboot or network disconnection.

When working on remote servers, especially through SSH, physical intervention like disconnecting cables is not feasible. In such scenarios, using command-line tools to terminate the user's active processes is a more efficient and controlled method. It allows for minimal disruption to the rest of the system.

Linux provides several commands to log out a user by ending their session or killing their processes. This process targets only the specific user's activities, ensuring that other users on the system are unaffected. Understanding how to execute these commands will allow you to enforce session terminations without risking system-wide issues.

Steps to force user logout in Linux:

  1. Open the terminal on your Linux system.
  2. Display the currently logged-in users.
    $ who
    user     :0           2021-01-23 16:23 (:0)
    shakir   pts/1        2021-01-23 16:31 (192.168.111.1)
  3. Identify the user to log out.

    The username and terminal type (e.g., pts/1) will help you identify the user session.

  4. List all processes associated with the user.
    $ ps -U shakir
        PID TTY          TIME CMD
       2086 ?        00:00:00 systemd
       2087 ?        00:00:00 (sd-pam)
       2093 ?        00:00:00 pulseaudio
       2097 ?        00:00:00 tracker-miner-f
       2106 ?        00:00:00 dbus-daemon
       2126 ?        00:00:00 gvfsd
       2135 ?        00:00:00 gvfsd-fuse
       2136 ?        00:00:00 gvfs-udisks2-vo
       2149 ?        00:00:00 gvfs-mtp-volume
       2153 ?        00:00:00 gvfs-goa-volume
       2157 ?        00:00:00 goa-daemon
       2177 ?        00:00:00 goa-identity-se
       2186 ?        00:00:00 gvfs-afc-volume
       2194 ?        00:00:00 gvfs-gphoto2-vo
       2248 ?        00:00:00 sshd
       2249 pts/1    00:00:00 bash
  5. Terminate the specific session by killing the related processes.
    $ sudo kill 2249
    [sudo] password for user:

    bash is the user's shell session. Terminating this will log out the user.

  6. Alternatively, end all processes owned by the user.
    $ sudo pkill -u shakir
  7. If needed, force terminate any remaining processes.
    $ sudo pkill -9 -u shakir
  8. Verify the user has been logged out.
    $ who
    user     :0           2021-01-23 16:23 (:0)
Discuss the article:

Comment anonymously. Login not required.