Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Disconnect Inactive or Idle SSH Connections in Linux?
Secure Shell (SSH) is a protocol that enables secure communication between two systems. In Linux, SSH is widely used to remotely access and manage servers. However, idle or inactive SSH connections can pose security risks and consume system resources unnecessarily. This article explains how to identify and disconnect such connections to maintain system security and performance.
Identifying Inactive or Idle SSH Connections
Before disconnecting inactive SSH connections, you must first identify them. Linux provides several commands to list active users, display session information, and monitor connection states.
Using the 'who' Command
The who command displays currently logged-in users along with their login information. Use the -u option to show idle time for each session:
who -u
This output shows the username, terminal, login time, idle duration, and process ID for each active session.
Using the 'w' Command
The w command provides detailed information about logged-in users and their current activities:
w
The output includes user names, terminals, remote hosts, login times, idle times, and currently running processes. The IDLE column shows how long each user has been inactive.
Using the 'last' Command
The last command displays a history of user logins and logouts:
last
This helps identify patterns of user activity and detect sessions that may have been left open unintentionally.
Disconnecting Inactive SSH Connections Manually
Once you've identified idle connections, you can terminate them using various commands that target specific processes or users.
Using the 'kill' Command
To terminate a specific SSH session, use the kill command with the process ID obtained from the who -u command:
kill [PID]
For a more forceful termination, use the -9 signal:
kill -9 [PID]
Using the 'pkill' Command
To disconnect all SSH connections for a specific user:
pkill -u [username]
This command terminates all processes owned by the specified user, effectively ending their SSH sessions.
Using the 'skill' Command
For more targeted termination, use the skill command to end sessions on specific terminals:
skill -KILL -u [username] --tty=[terminal]
This approach allows you to terminate sessions on particular terminals while preserving others.
Automating Disconnection of Inactive SSH Connections
Manual disconnection is not scalable for production environments. Here are two automated approaches to handle idle SSH connections.
Creating an Automated Script Using Cron Jobs
Create a script that automatically identifies and terminates idle sessions. First, create the script:
#!/bin/bash
# Script to disconnect idle SSH sessions
IDLE_THRESHOLD=1800 # 30 minutes in seconds
# Get list of users with SSH sessions
users=$(who | awk '{print $1}' | sort -u)
for user in $users; do
# Check idle time for each user
idle_time=$(w -h "$user" | awk '{print $5}' | head -n1)
# Convert idle time to seconds if needed and compare
if [[ "$idle_time" =~ ^[0-9]+$ ]] && [[ "$idle_time" -gt "$IDLE_THRESHOLD" ]]; then
echo "Disconnecting idle user: $user (idle for $idle_time seconds)"
pkill -u "$user"
fi
done
Make the script executable and add it to crontab:
chmod +x /path/to/disconnect_idle.sh crontab -e
Add the following line to run the script every 5 minutes:
*/5 * * * * /path/to/disconnect_idle.sh
Setting Up Automatic Disconnection Using sshd_config
A more elegant solution is configuring SSH server timeouts directly. Edit the SSH daemon configuration:
sudo nano /etc/ssh/sshd_config
Add or modify these parameters:
ClientAliveInterval 300 ClientAliveCountMax 2
These settings configure the SSH server to:
ClientAliveInterval 300 Send keep-alive messages every 300 seconds (5 minutes)
ClientAliveCountMax 2 Allow up to 2 unanswered keep-alive messages before disconnecting
This results in automatic disconnection after 10 minutes of inactivity (5 minutes × 2 attempts). Restart the SSH service to apply changes:
sudo systemctl restart sshd
Best Practices
| Method | Pros | Cons | Use Case |
|---|---|---|---|
| Manual Commands | Immediate control, selective | Time-consuming, not scalable | One-off situations |
| Cron Scripts | Flexible logic, customizable | Requires maintenance | Complex environments |
| SSH Server Config | Built-in, reliable, automatic | Global settings only | Production servers |
Conclusion
Managing inactive SSH connections is crucial for system security and resource optimization. The SSH server configuration method provides the most reliable automated solution, while manual commands offer immediate control for specific situations. Implementing proper timeout policies helps prevent unauthorized access and maintains efficient resource utilization.
