How to Disconnect Inactive or Idle SSH Connections in Linux?


Introduction

Secure Shell or SSH is a protocol that enables secure communication between two systems. In Linux, SSH is widely used to remotely access and manage servers. The tool establishes a secure connection between the client and server, encrypting the information being transmitted so that it can’t be intercepted by unauthorized entities.

In Linux, SSH connections are created when a user logs in to a remote machine via the command-line interface. The user can execute commands on the remote host as if they were physically present on that machine. This way, system administrators and network engineers can manage multiple machines from a single terminal or workstation without having to switch devices constantly.

Identifying Inactive or Idle SSH Connections

Before disconnecting inactive or idle SSH connections, it is important to first identify them. In Linux, there are several commands that can be used to list active users and their sessions, display information about logged-in users and their processes, and view a log of previous logins and sessions.

Using the 'who' command to list active users and their sessions

The 'who' command is used to display a list of currently logged-in users along with their login name, terminal line number (tty), login time, and remote hostname or IP address. To specifically view only SSH connections, the '-u' option can be added to the command. This will display only active SSH connections with the corresponding user information.

who -u

Using the 'w' command to display information about logged-in users and their processes

The 'w' command provides detailed information about all logged-in users including what they are doing on the system. The output includes columns for the user's name, terminal number, remote host address, login time as well as processes running under each user. Simply typing in ‘w’ on the terminal will give you all these details for every individual connected onto your system through any means including ssh , console , GUI etc.

Using the 'last' command to view a log of previous logins and sessions

The 'last' command displays a list of all previously logged in users sorted by most recent first. It also shows when they logged in last time from which location/terminal/IP . One other important piece of information that ‘last’ provides is if there were any unexpected terminations such as power failure or network outage etc.

last

Knowing the various commands used to identify inactive or idle SSH connections is crucial in maintaining a secure and efficient system.

Disconnecting Inactive or Idle SSH Connections Manually

If you have identified an inactive or idle SSH connection and want to terminate it manually, there are several commands that you can use to do so. These commands specifically target the processes associated with the SSH connection, allowing you to end them without affecting any other processes on your system.

Using the 'kill' command to terminate a specific session ID

The 'kill' command is used to send a signal to a particular process (or multiple processes) in order to terminate them. When it comes to disconnecting an inactive or idle SSH connection, you can use 'kill' with the session ID associated with that particular connection.

To determine the session ID of an inactive or idle SSH connection, you can use any of the methods mentioned in section two of this article. Once you have determined the session ID, simply run the following command −

kill [sessionID]

This will immediately terminate that specific SSH connection and log out any user associated with it.

Using the 'pkill' command to kill all processes associated with a specific user

If you want to disconnect all inactive or idle SSH connections for a particular user at once, then you can use the 'pkill' command. This command sends a signal not only to a specific process but also kills all other related processes as well. To terminate all connections for one particular user, run this command −

pkill -U [username]

This will send signals and end all ssh connections opened by [username].

Using the 'skill' command to send a signal to terminate specific processes

Sometimes using kill or pkill methods may terminate other associated processes also with an active session. It is not always easy to determine which of these processes are associated with the active SSH connection, so you can use the 'skill' command instead. The 'skill' command allows you to target specific processes by name, user or group.

You can use it to send a signal that will terminate any process that matches a particular pattern. To kill a particular ssh session run this command −

skill -KILL -u [username] --tty=[terminal] This will send a signal to end all ssh connections opened by [username] on the specified terminal. The skill command could terminate additional processes also running in the terminal.

Automating Disconnection of Inactive or Idle SSH Connections

In this section, we will discuss two methods for automating the disconnection of inactive or idle SSH connections in Linux: creating an automated script using cron jobs and setting up automatic disconnection using sshd_config file.

Creating an Automated Script Using Cron Jobs

Cron is a time-based job scheduler in Linux that allows you to automate tasks by scheduling them to run at specific intervals. To create an automated script for disconnecting inactive or idle SSH connections, you can use a combination of commands we discussed earlier: 'who', 'w', 'last', 'kill', and/or 'skill'.

You can write a simple Bash script that checks for inactive sessions and kills them automatically. First, open your terminal and type −

$ crontab -e

This command will open the crontab file in edit mode. Then add the following line at the end of the file −

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

This tells cron to execute our script every minute. Next, create a new Bash script by typing −

$ nano /path/to/script.sh

Now copy and paste this code into the file −

#!/bin/bash 

users=$(who | awk '{print $1}' | sort -u) for user in $users 
do idle=$(w -h "$user" | awk '{print $5}') 
if [[ "$idle" -gt "1800" ]]; then pkill -u "$user" 
fi done

This script will check for idle sessions every minute and kill the sessions of users who have been idle for more than 30 minutes (1800 seconds). You can change this threshold by modifying the number in the 'if' statement.

Setting Up Automatic Disconnection Using sshd_config File

Another way to automate disconnection of inactive SSH connections is by modifying the sshd_config file. This file contains configuration settings for the SSH server, including session timeout values. By default, SSH sessions do not have a timeout value, which means that idle sessions will remain open indefinitely.

To set a session timeout value −

Open your terminal and type −

$ sudo nano /etc/ssh/sshd_config

Add or modify the following line−

ClientAliveInterval 300 ClientAliveCountMax 2

The above configuration sets a session timeout value of five minutes (300 seconds). The 'ClientAliveCountMax' option specifies how many times the server should send a keep-alive message to the client before terminating an inactive session.

Save and close the file using CTRL+X, then Y, then ENTER.

Restart SSH service with command below −

$ sudo systemctl restart sshd.service

This configuration will ensure that inactive sessions are terminated after five minutes. If there is no activity during this period, the server will send a keep-alive message to the client twice before terminating an inactive session. Automating disconnection of inactive or idle SSH connections is essential for maintaining system security and performance.

Conclusion

As we have seen, idle or inactive SSH connections can pose a security risk to your Linux server. If these connections are left unattended, an attacker could potentially take control of the dormant session and gain unauthorized access to your system. Therefore, it is crucial to keep track of active SSH sessions and disconnect idle or inactive ones promptly.

Updated on: 11-Jul-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements