How to Disconnect Inactive or Idle SSH Connections in Linux? (2024)

How to Disconnect Inactive or Idle SSH Connections in Linux? (1)

  • Trending Categories
  • Data Structure
  • Networking
  • RDBMS
  • Operating System
  • Java
  • MS Excel
  • iOS
  • HTML
  • CSS
  • Android
  • Python
  • C Programming
  • C++
  • C#
  • MongoDB
  • MySQL
  • Javascript
  • PHP
  • Physics
  • Chemistry
  • Biology
  • Mathematics
  • English
  • Economics
  • Psychology
  • Social Studies
  • Fashion Studies
  • Legal Studies
  • Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Effective Resume Writing
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

LinuxOperating SystemOpen Source

';

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.

Satish Kumar

Updated on: 11-Jul-2023

12K+ Views

  • Related Articles
  • 4 Ways to Speed Up SSH Connections in Linux
  • How to Change SSH Port in Linux?
  • How to Mount Remote Linux Filesystem or Directory Using SSHFS Over SSH?
  • How to Increase SSH Connection Timeout in Linux
  • How to Disable SSH Root Login in Linux?
  • How to Brute-Force SSH in Kali Linux?
  • How to Find All Failed SSH login Attempts in Linux?
  • How to Fix No route to host SSH Error in Linux?
  • How to List All Connected SSH Sessions on Linux
  • Copying SSH Keys to different Linux Machine
  • Common SSH Commands in Linux With Examples
  • How to use OpenSSH Multiplexer To Speed Up OpenSSH Connections on Linux
  • How to resume a partially transferred file over ssh on Linux?
  • How to Enable SSH on Raspberry Pi {Linux, Mac OS, Windows}?
  • Keeping SSH session alive on Linux
Kickstart Your Career

Get certified by completing the course

Get Started

How to Disconnect Inactive or Idle SSH Connections in Linux? (31)

Advertisem*nts

';

How to Disconnect Inactive or Idle SSH Connections in Linux? (2024)

FAQs

How to Disconnect Inactive or Idle SSH Connections in Linux? ›

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

How to disconnect SSH session in Linux? ›

If you wish to end the SSH session gracefully, type exit or logout in the terminal window and press Enter. This sends a request to the remote server to close the connection. 2. Alternatively, you can forcefully close the session by clicking the X button in the top-right corner of the Putty window.

How do I interrupt SSH connection in Linux? ›

We can use a Secure Shell (SSH) connection to access a remote server and execute commands therein. The usual way to interrupt such a command is by pressing Ctrl+C.

How do I break out of SSH on Linux? ›

But: you can just close the SSH session with an escape sequence: next time, just do Enter + ~ + . ! So just press the enter key, followed by the tilde key followed by the dot - and you should be back to your terminal!

How do I disable SSH inactivity timeout? ›

Avoid SSH timeout from the client
  1. Edit the SSH client configuration file using a text editor. ...
  2. Add the ServerAliveInterval option with a value, such as 30 seconds. ...
  3. Save the changes to the client configuration file.
  4. Alternatively, specify the ServerAliveInterval option directly in the command line when connecting via SSH.

How to disconnect inactive or idle SSH connections in Linux? ›

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.

How to disable SSH on Linux? ›

To disable the SSH root login:
  1. Open the SSH configuration file sshd_config with the text editor vi: vi /etc/ssh/sshd_config.
  2. In the line PermitRootLogin yes replace the word Yes with the word No.
  3. Save the file.
  4. Restart the service. Ubuntu. service ssh restart. CentOS 7. systemctl restart sshd.

Does SSH automatically disconnect? ›

SSH servers often have an idle timeout period, after which they automatically disconnect idle sessions. To prevent premature disconnections, consider modifying the server's idle timeout setting. To modify the idle timeout: Locate the SSH server configuration file, typically located at /etc/ssh/sshd_config .

How do I disconnect TCP connection in Linux? ›

Use the DRop/-D command to terminate an individual TCP connection when you do not want to terminate the server itself, but want only to drop an individual connection with that server. Use the DROP/-D command to terminate old TCP connections if they prevent a server from being restarted.

How to detach process Linux SSH? ›

Then, press Ctrl + A and then Ctrl + D. This will "detach" your screen session, but leave your process running, and you can leave your SSH session. If you connect via SSH to the remote server at a later time, you can type screen -r to see the screen with the runner and Ctrl + A and Ctrl + D to detach again.

How do I close all SSH connections? ›

How do I exit an SSH connection in Windows?
  1. Typing exit + enter.
  2. Typing enter + ~
  3. Typing enter + ~ + &
  4. Typing enter + ~ + ctrl + z.
  5. Typing the above but with a space after the tilde, because dead keys are on for my keyboard layout.
  6. Typing Ctrl + d.
  7. Typing Ctrl + c.
  8. Typing Ctrl +\
Mar 27, 2021

How to shutdown SSH Linux? ›

Log into the server, if you haven't already:
  1. $ ssh [email protected]. Then type in:
  2. $ reboot. If you're not in as root, you need the sudo it:
  3. $ sudo reboot. It takes a minute or two to boot. ...
  4. $ shutdown. It will schedule the shutdown in one minute. ...
  5. $ shutdown -c. The now param shuts the system down immediately:
  6. $ shutdown now.

How to check SSH connections in Linux? ›

To list all connected SSH sessions, you can use the “who -a” command. The -a option shows all users, including those who are not logged in through the system console. The result will show your username, terminal, and login date and time.

How to time out SSH in Linux? ›

The SSH connection timeout is the period of inactivity after which the SSH server will terminate the connection. By default, most SSH servers have a connection timeout of 15 minutes. This means that if you do not interact with the remote system for more than 15 minutes, the connection will be terminated.

How do I keep my SSH connection alive longer? ›

Keeping SSH connections alive
  1. Start PuTTY.
  2. Load your connection session.
  3. In the Category pane, click Connection.
  4. Under Sending of null packets to keep session active, in the Seconds between keepalives, type 240. ...
  5. In the Category pane, click Session.
  6. Click Save.
  7. Connect to your account and monitor the connection.

How to disable SSH command? ›

Right-click a node, then select Commands > Enable SSH or Commands > Disable SSH.

How to detach a SSH session? ›

Press Ctrl B then hit D to detach the session. Re-detach from the session.

How do I get disconnected from SSH? ›

Since SSH operates over a single TCP connection, if the underlying TCP connection is disconnected, so is the SSH connection. The disconnection occurs only when data transmission actually fails, so when the communication is physically impossible and no activity occurs on SSH , the connection may last longer.

How to terminate a session in Linux? ›

You can use the SIGHUP, SIGKILL, or SIGTERM termination signals to initiate the Linux kill process. Use the sudo command to ensure you have the proper permissions for terminating a process.

Top Articles
You’ve filed your tax return, but you forgot something. Now what?
How Does Crypto Voucher Work? [+Definition, Redeeming Process, & More]
Hometown Pizza Sheridan Menu
Friskies Tender And Crunchy Recall
Places 5 Hours Away From Me
biBERK Business Insurance Provides Essential Insights on Liquor Store Risk Management and Insurance Considerations
What is IXL and How Does it Work?
12 Best Craigslist Apps for Android and iOS (2024)
What Does Dwb Mean In Instagram
Newgate Honda
Blog:Vyond-styled rants -- List of nicknames (blog edition) (TouhouWonder version)
104 Whiley Road Lancaster Ohio
Nwi Arrests Lake County
Kvta Ventura News
Trac Cbna
Touchless Car Wash Schaumburg
Jail View Sumter
Jeffers Funeral Home Obituaries Greeneville Tennessee
Naval Academy Baseball Roster
Synergy Grand Rapids Public Schools
2011 Hyundai Sonata 2 4 Serpentine Belt Diagram
Doctors of Optometry - Westchester Mall | Trusted Eye Doctors in White Plains, NY
Safeway Aciu
Intel K vs KF vs F CPUs: What's the Difference?
How do you get noble pursuit?
1636 Pokemon Fire Red U Squirrels Download
Movies - EPIC Theatres
Evil Dead Rise Showtimes Near Regal Sawgrass & Imax
Xfinity Outage Map Lacey Wa
Gerber Federal Credit
Petsmart Distribution Center Jobs
Truis Bank Near Me
Appleton Post Crescent Today's Obituaries
Edward Walk In Clinic Plainfield Il
Http://N14.Ultipro.com
W B Crumel Funeral Home Obituaries
Ket2 Schedule
R&J Travel And Tours Calendar
Regis Sectional Havertys
Duff Tuff
Boone County Sheriff 700 Report
Timberwolves Point Guard History
R: Getting Help with R
Avance Primary Care Morrisville
Jane Powell, MGM musical star of 'Seven Brides for Seven Brothers,' 'Royal Wedding,' dead at 92
Vci Classified Paducah
Online College Scholarships | Strayer University
F9 2385
Tyrone Unblocked Games Bitlife
O'reilly's On Marbach
Parks And Rec Fantasy Football Names
Famous Dave's BBQ Catering, BBQ Catering Packages, Handcrafted Catering, Famous Dave's | Famous Dave's BBQ Restaurant
Latest Posts
Article information

Author: Jamar Nader

Last Updated:

Views: 5678

Rating: 4.4 / 5 (75 voted)

Reviews: 90% of readers found this page helpful

Author information

Name: Jamar Nader

Birthday: 1995-02-28

Address: Apt. 536 6162 Reichel Greens, Port Zackaryside, CT 22682-9804

Phone: +9958384818317

Job: IT Representative

Hobby: Scrapbooking, Hiking, Hunting, Kite flying, Blacksmithing, Video gaming, Foraging

Introduction: My name is Jamar Nader, I am a fine, shiny, colorful, bright, nice, perfect, curious person who loves writing and wants to share my knowledge and understanding with you.