Skip to Content

2 ways to automatically terminate idle sessions in a Linux system

You can utilize systemd-logind configurations or set up a custom script to terminate idle sessions. Here are the two methods. We have verified on RHEL Linux.

Using systemd-logind (For Systems with systemd)

  1. Edit logind.conf: Open the /etc/systemd/logind.conf file in a text editor. You’ll need administrative privileges to edit this file.
    sudo vi /etc/systemd/logind.conf
  2. Configure StopIdleSessionSec:  Add this line and set it as needed. For example: StopIdleSessionSec=900
  3. Reload logind: After making changes, reload the systemd-logind service to apply them.
    sudo systemctl restart systemd-logind

Using a Custom Script (For Systems without systemd or Additional Flexibility)

  1. Create a Script: Write a script to check for idle users and kill their processes if they have been idle for longer than a specified threshold. Here’s a simple example script:
    #!/bin/bash
    
    IDLE_LIMIT=3600 # Set your idle time limit in seconds
    
    who -u | awk -v idle_limit=$IDLE_LIMIT '{ if ($6 != "old" && $6 != "." && ($6 * 60) > idle_limit) print $1, $2; }' | while read user tty
    do
        pkill -KILL -t "$tty"
        echo "Killed session on $tty for idle user $user"
    done
  2. Set Execute Permission: Make the script executable.
    chmod +x /path/to/script.sh
  3. Cron Job: Schedule the script to run at regular intervals using cron.
    crontab -e

    Add a line like this to run the script every 10 minutes:

    */10 * * * * /path/to/script.sh

Notes

  • Testing: Always test these methods in a non-critical environment first to ensure they work as expected and do not disrupt normal operations.
  • Customization: Adjust the idle time thresholds according to your requirements.
  • User Communication: If you’re managing a multi-user system, it’s good practice to inform users about the auto-termination of idle sessions to prevent data loss.