Keeping idle shell sessions to a Linux server is possible a security risk. Not to forget that it would consume system resources.
Okay, maybe not a single idle session but imagine if you have multiple users accessing the same Linux system remotely and leaving their sessions idle.
As a Linux sysadmin, you can see which users are logged in on the system and how long have they been idle.
You may manually kick the idle user out but that's tiresome and certainly not very productive.
Let me show you how to automatically logout idle users from their shell.
Method 1: Use TMOUT to auto logout users from idle shell sessions
In bash and other shells, you can use the
TMOUT variable to set the idle logout time. If there is no activity from the user for this time period, the shell session will be closed.
Check if the TMOUT is already set. The values are in seconds.
To test, you can use it like this:
This will close your terminal session or SSH session after 300 seconds, i.e. 5 minutes.
For SSH sessions, you should see a message like this:
[email protected]:~# timed out waiting for input: auto-logout Connection to 126.96.36.199 closed.
For local sessions, your terminal should be closed automatically.
But you probably already know that it is not the best way to set an environment variable. You can either set it in individual user's profile (or bash profile) or you set it for all the users, system wide, from /etc/profile.
Assuming that you are a sysadmin and you want to auto logout idle users on your Linux server, set it at system level.
Open the /etc/profile file in a text editor like Vim or Nano:
And add the following line to it:
Save and close the file. From now onward, any user with 5 minutes of inactivity will be logged out automatically.
This works for both local and remote sessions. If you want to set it only for SSH sessions, the next method is what you could use.
Method 2: Automatically logout users from idle SSH sessions
You can configure SSH server to force logout a user after certain inactivity period.
Edit the SSH config file (/etc/ssh/sshd_config):
sudo nano /etc/ssh/sshd_config
Look for the following two variables and remove the # before their starting line and set values like this:
ClientAliveInterval 200 ClientAliveCountMax 3
Save and close the file.
This means that the server will send a keep alive message to the client every 200 seconds for 3 times. If it receives no response (meaning the user is idle), it will close the session at 600 seconds (200*3).
You can choose suitable values based on your requirement.
This is SSH only method and will not impact the local shell sessions.
I hope you find this Linux tip on automatically logging out users helpful. Do subscribe for more Linux sysadmin tips.