Managing server connections efficiently is crucial for maintaining a smooth and secure IT environment. One such common challenge is dealing with inactive SSH sessions. These sessions can clutter your server, consuming resources and potentially posing security risks.
In this article, we’ll explore practical methods to identify and terminate these idle connections. We’ll delve into the use of commands like pstree
and htop
, offering step-by-step guidance to keep your server streamlined and secure.
Table of Contents
Using w
or pstree
to Identify then Kill Idle SSH Sessions
Contents
- 1 Using w or pstree to Identify then Kill Idle SSH Sessions
- 2 Using ps and grep to Identify and Kill Inactive SSH Sessions
- 3 Using htop to Identify and Kill Idle SSH Sessions
- 4 Automating the Process with a script (ssh_idle_killer.sh)
- 5 Automatically kill idle SSH sessions by editing sshd_config
- 6 Conclusion
Using for example the “w” command, you see something like the following:
22:47:28 up 315 days, 21:09, 2 users, load average: 9.04, 8.17, 7.30 USER TTY FROM LOGIN@ IDLE JCPU PCPU WHAT root pts/0 ipxxx-xxx-xxx-xxx 23:54 26:40 9.26s 0.86s -bash root pts/1 ipxxx-xxx-xxx-xxx 22:44 0.00s 0.00s 0.00s w
There are a few ways to kill idle ssh sessions. Including editing your sshd_config, discussed below. But here’s an easy after-the-fact method:
Run the pstree
command:
pstree -p
the output will look something like this:
├─sshd(3102)─┬─sshd(3649)───bash(3656)
│ └─sshd(16680)───bash(16687)───pstree(17073)
Now look for the session’s parent PID from the line without the “pstree” command. The line including “pstree” would be your session! 🙂
To kill the idle ssh session, type:
kill 3649
Replace 3649 with your idle ssh session PID. Check afterward with the “w” command.
Now to prevent this from happening in the future, lets edit /etc/ssh/sshd_config and add these two config lines:
ClientAliveInterval 600 ClientAliveCountMax 3
Using ps
and grep
to Identify and Kill Inactive SSH Sessions
An alternative and effective method to manage and kill idle SSH sessions involves using the ps
(process status) and grep
commands. This approach allows you to directly target and terminate SSH sessions that have been inactive.
Identifying Idle SSH Sessions
To find idle SSH sessions, you can use ps
combined with grep
to filter SSH-related processes. Run the following command:
ps aux | grep sshd:
This command lists all active SSH sessions. Each line represents a session, and the first number after the username is the process ID (PID) of the session.
Determining Which Sessions are Idle
Determining idleness can be somewhat subjective and depends on the specific criteria you set (like CPU usage, time since last activity, etc.). However, as a basic approach, you could look for sessions with low CPU and memory usage, indicating potential idleness.
Killing the Idle Session
Once you have identified an idle session’s PID, you can terminate it using the kill
command. For example:
kill [PID]
Replace [PID]
with the actual process ID of the idle SSH session. This command sends a signal to terminate the session.
Using htop to Identify and Kill Idle SSH Sessions
Another method for identifying idle (orphaned ssh sessions) is by using htop. Notice below the inactive ssh session with the ‘top’ command left running. Also, see htop: Quick Guide & Customization, 90 frequently used Linux Commands, and top, atop, others.
Automating the Process with a script (ssh_idle_killer.sh
)
For a more automated approach, you can write a script that periodically checks for idle SSH sessions and kills them based on specific criteria (like duration of inactivity). Be cautious with automation, though, as it might inadvertently terminate active sessions if not configured correctly.
Below is a sample Bash script that you can modify and use to kill inactive SSH sessions. The script checks for SSH sessions that have been idle for a specified amount of time and terminates them:
#!/bin/bash # SSH Idle Session Killer Script # Threshold for idle time in seconds (e.g., 3600 seconds = 1 hour) IDLE_THRESHOLD=3600 # Log file for recording killed sessions LOG_FILE="/var/log/ssh_idle_killer.log" # Current date and time for logging current_date=$(date '+%Y-%m-%d %H:%M:%S') # Function to log actions log_action() { echo "$current_date: $1" >> $LOG_FILE } # Checking for idle SSH sessions echo "Checking for idle SSH sessions..." ps -eo pid,etimes,comm | grep sshd: | while read line; do # Extract PID and elapsed time of the session PID=$(echo $line | awk '{print $1}') ELAPSED_TIME=$(echo $line | awk '{print $2}') # Check if the session is idle beyond the threshold if [ $ELAPSED_TIME -gt $IDLE_THRESHOLD ]; then # Kill the idle session kill $PID # Log the action log_action "Killed idle SSH session with PID $PID after $ELAPSED_TIME seconds of inactivity." fi done echo "Idle SSH session check complete."
ssh_idle_killer.sh
Script Modification Instructions
- Set Idle Threshold: Modify the
IDLE_THRESHOLD
variable to set the time (in seconds) after which an SSH session should be considered idle. - Log File: The script logs its actions to a file specified by
LOG_FILE
. You can change the path as needed. - Running the Script:
- Make the script executable:
chmod +x ssh_idle_killer.sh
- Run the script:
./ssh_idle_killer.sh
- Make the script executable:
- Automation (Optional): If you want to run this script periodically, you can set up a cron job.
- Caution (You have been warned!): Test this script in a controlled environment before deploying it in a production environment to ensure it behaves as expected.
This script provides a basic structure. You can expand or modify it according to your specific requirements or to add more sophisticated checks for idleness.
Automatically kill idle SSH sessions by editing sshd_config
To automatically kill idle SSH sessions by editing the default sshd_config
file, you can utilize the ClientAliveInterval
and ClientAliveCountMax
options. These settings control how long the server waits before disconnecting idle sessions. Here’s a brief guide on how to do it:
Editing the sshd_config
File
- Open the SSHD Config File:
Open thesshd_config
file in your preferred text editor. This file is typically located at/etc/ssh/sshd_config
. For example, you can usevi
:
sudo vi /etc/ssh/sshd_config
- Set
ClientAliveInterval
:
This option sets a timeout interval in seconds. After this interval, if no data has been received from the client, the server will send a message via the encrypted channel to request a response. Add or modify this line:
ClientAliveInterval 300
Here, 300
is the number of seconds (5 minutes). You can adjust this value based on your requirements.
- Set
ClientAliveCountMax
:
This option defines the maximum number of client alive messages which may be sent without receiving any messages back from the client. If this threshold is reached, the client session is terminated. Add or modify this line:
ClientAliveCountMax 3
This setting means that the server will send up to 3 alive messages, each 5 minutes apart. If no response is received, the session will be terminated (total idle time of 15 minutes in this example).
- Save and Close the File:
After adding or modifying these lines, save and close the file. - Restart the SSH Service:
For the changes to take effect, restart the SSH service:
sudo systemctl restart sshd
Notes:
- Be mindful of setting these intervals too low, as it could lead to frequent disconnections, especially in environments where idle times are common.
- Some SSH clients might not respond to the server’s alive messages, leading to unintentional disconnections.
- While automatically killing idle sessions enhances security, it may interrupt workflows. Balance these settings based on your security needs and user experience.
By configuring these options in your sshd_config
file, you create an automated way to keep your server free from idle SSH sessions, enhancing both security and resource management.
Conclusion
Efficiently managing idle SSH sessions is crucial for maintaining the security and performance of your server. This article has explored several methods to identify and terminate these inactive sessions. From using commands like w
, pstree
, and ps
combined with grep
, to implementing a custom script, each method offers unique advantages to suit different server environments and administrative preferences.
The provided script serves as a practical tool to automate the process of killing idle SSH sessions based on a defined idle threshold, ensuring your server remains efficient and secure. Remember, it’s important to tailor these solutions to your specific needs and test them thoroughly in a controlled environment before implementation.
Managing SSH sessions effectively optimizes server resources and enhances security, making it an essential practice for any system administrator. By applying these methods, you can ensure a more robust and reliable server management experience.
Published: December 9th, 2013 | Last updated: January 23th, 2024