- 6 commands to check and list active SSH connections in Linux
- Check active SSH connections
- 1. Using ss command
- 2. Using last command
- 3. Using who command
- 4. Using w command
- 5. Using netstat command
- Как мне выйти из SSH-соединения?
- Escape-символ SSH и последовательность отключения
- Другие последовательности побега
- How to disconnect idle ssh session or keep idle ssh session active in Linux
- What is an idle SSH session?
- Disconnect idle SSH session (ssh close connection after sometime)
- Keep idle SSH session active (ClientAliveInterval & ClientAliveCountMax)
- Related Posts
- How to kill or disconnect hung ssh session in Linux
- What is an unresponsive SSH session?
- Terminate stuck ssh session
- Automatically disconnect hung SSH session
- Method 1:
- Method 2:
- Method 3:
- Use timeout to kill SSH session
- Disconnect PSSH session
- Related Posts
- 2 thoughts on “How to kill or disconnect hung ssh session in Linux”
6 commands to check and list active SSH connections in Linux
Table of Contents
How to check active SSH connections in Linux. Show SSH connection history. How to show active ssh sessions in Linux. List all the active SSH connections in Unix. Find out all the currently active ssh connections on any Linux node. Which all tools can be used to list all the active ssh connections in Linux. Show active SSH sessions. Check ssh connection history using log files in Linux.
Some more more articles you may be interested on similar topics:
Check active SSH connections
There are various commands and tools available in Linux which can be used to check active SSH connections or sessions on your Linux node. In this article I will share a list of tools which can be used to get the list of active SSH connections. If you are aware of any more commands to show active ssh sessions then please let me know via comment section.
1. Using ss command
ss is used to dump socket statistics. It allows showing information similar to netstat . It can display more TCP and state information than other tools. We will use grep function to only get the list of active SSH sessions on our local host
From the above example we know that there are three hosts which are currently connected to our node3. We have active SSH connections from 10.0.2.31, 10.0.2.30 and 10.0.2.2
2. Using last command
last searches back through the file /var/log/wtmp (or the file designated by the -f flag) and displays a list of all users logged in (and out) since that file was created. Names of users and tty’s can be given, in which case last will show only those entries matching the arguments.
Using this command you can also get the information about the user using which the SSH connection was created between server and client. So below we know the connection from 10.0.2.31 is done using ‘deepak‘ user, while for other two hosts, ‘root‘ user was used for connecting to node3.
Here I am grepping for a string «still» to get all the patterns with » still logged in «. So now we know we have three active SSH connections from 10.0.2.31, 10.0.2.30 and 10.0.2.2
3. Using who command
who is used to show who is logged on on your Linux host. This tool can also give this information
Using this command we also get similar information as from last command. Now you get the user details used for connecting to node3 from source host, also we have terminal information on which the session is still active.
4. Using w command
w displays information about the users currently on the machine, and their processes. This gives more information than who and last command and also serves our purpose to get the list of active SSH connections. Additionally it also gives us the information of the running process on those sessions.
Using w command you will also get the idle time details, i.e. for how long the session is idle. If the SSH session is idle for long period then it is a security breach and it is recommended that such idle SSH session must be killed, you can configure your Linux host to automatically kill such idle SSH session.
5. Using netstat command
Similar to ss we have netstat command to show active ssh sessions. Actually we can also say that ss is the new version of netstat. Here we can see all the ESTABLISHED SSH sessions from remote hosts to our localhost node3. it is also possible that one or some of these active ssh connections are in hung state so you can configure your host to automatically disconnect or kill these hung or unresponsive ssh sessions in Linux.
Источник
Как мне выйти из SSH-соединения?
Я подключаюсь к серверу через SSH, чтобы отправить сообщение серверу сокетов с помощью команды вроде:
После того, как соединение установлено, и я пишу сообщение и отправляю его, я не могу выйти из текстового режима. Мне только разрешено вводить больше текста и все.
Есть ли команда или комбинация клавиш, которая позволяет мне вернуться в командный режим?
Как мне выйти из SSH-соединения?
- закрытие сеанса оболочки, например, с exit последующим Enter , или Ctrl — d обычно позволяет вам ssh нормально выйти из сеанса,
- в случае, если у вас плохое соединение и оболочка не отвечает, нажмите Enter клавишу, затем введите
. и ssh должен немедленно закрыться и вернуть вас в командную строку.
Первый вариант должен быть интуитивно понятным, но как мы узнаем последний вариант?
Мы могли бы узнать эту информацию из внимательного прочтения справочной страницы.
дает нам документацию по SSH , в которой есть следующий раздел о escape-символах:
Краткий ответ: Тип exit
Если это не сработает, однако .
Escape-символ SSH и последовательность отключения
В большинстве реализаций SSH для интерактивных сессий используется escape-символ, аналогичный Ctrl-] комбинации telnet . Экранирующий символ SSH по умолчанию
вводится в начале строки.
Если вы хотите прекратить интерактивный сеанс OpenSSH, который застрял и не может быть завершен путем входа exit или Ctrl D в оболочку на удаленной стороне , вы можете ввести,
за которым следует точка . . Чтобы быть уверенным, что необходимо вводить escape-символ в начале строки ввода, сначала нужно нажать Enter. Таким образом, следующая последовательность завершит сеанс SSH в большинстве случаев:
Другие последовательности побега
Например, OpenSSH предлагает другие escape-последовательности
? во время сеанса должен дать вам список. Некоторые примеры:
затем Ctrl-Z приостанавливает сессию,
& помещает это непосредственно в фон,
# дает список переадресованных соединений в этом сеансе.
Если вы хотите , чтобы просто ввести тильду в начале строки, вы должны удвоить его:
Экранирующий символ можно изменить с помощью параметра командной строки -e . Если вы установите специальное значение -e none , экранирование будет отключено, и сеанс будет полностью прозрачным.
Источник
How to disconnect idle ssh session or keep idle ssh session active in Linux
Table of Contents
How to disconnect idle SSH session? Linux terminate ssh session. Linux SSH close connection after sometime. ssh idle timeout. keep idle ssh session active in Linux. disconnect idle ssh session timeout. ssh close session timeout. ssh timeout. ssh idle timeout Linux. Autodisconnect idle ssh session Linux. Kill inactive ssh session automatically in Linux. Automatically disconnect idle ssh session in Linux. terminate inactive ssh session in Unix. ssh close connection after time. how to disconnect from ssh
What is an idle SSH session?
Here we mean that a ssh connection was made between a host and a client but there has been no activity on this connection by the user and is considered idle. Here although the ssh session is not in stuck state. You can list all the active ssh connections and then check the idle time for individual source host.
In this article I will share the trick to disconnect an idle SSH session automatically and also to avoid getting disconnected for an idle SSH session. In my last article I had shared the steps and examples to terminate an unresponsive SSH session in Linux.
The trick to disconnect idle SSH session is to use below two arguments with proper values to achieve both the scenario i.e. to disconnect an idle SSH session and also to make sure your SSH session does not gets disconnected when idle
But before disconnecting any such ssh session it is also important to know the currently active SSH sessions on your Linux node. There are various ssh authentication methods using which you can connect to Linux nodes with or without password depending upon your requirement.
From the man page
Disconnect idle SSH session (ssh close connection after sometime)
To disconnect idle SSH session i.e. to ssh close connection after some time make sure ClientAliveCountMax is 0. Because when is 0, sshd will not send client alive messages and ssh close connection after sometime if client is inactive for time period as provided with ClientAliveInterval .
Look out for the current assigned value of ClientAliveCountMax in /etc/ssh/sshd_config on node2
Next assign a null value for ClientAliveCountMax in /etc/ssh/sshd_config on the client node which for me is node2
Now we should also assign a time interval for which the session will be allowed to be active when idle. This can be defined using ClientAliveInterval again in the /etc/ssh/sshd_config file on my client node i.e. node2
For the sake of this article I am giving 10 seconds as this interval period. You can change this value based on your requirement.
Restart the sshd service and check the status
Next let us initiate the SSH session from node1 to node2
Monitor the idle SSH session on node2 using ‘ w ‘ to make sure ssh close connection after some time when idle
As you see, after 10 seconds of idle ssh session from node1 to node2, the SSH close connection after sometime automatically. Below debug message is seen on my node1
So our idle SSH session gets disconnected automatically after waiting for 10 seconds.
Keep idle SSH session active (ClientAliveInterval & ClientAliveCountMax)
Now above I showed you the trick to make sure your idle SSH session gets automatically disconnected. Now if this is becoming a problem for you then you can increase the value of ClientAliveCountMax to a non-zero value.
Additionally you can also use TCPKeepAlive in your sshd_config on the client node.
From the man page of sshd_config:
For the sake of this article I will use below values
Here sshd will send messages, called Client Alive Messages, through the encrypted channel to request a response from client if client is inactive for 5 minutes. The sshd daemon will send these messages max three times. If this threshold is reached while Client Alive Messages are being sent, sshd will disconnect the idle ssh session on the client.
These values can also be used in combination with ServerAliveInterval and ServerAliveCountMax to automatically disconnect a hung or unresponsive SSH session.
Next restart the sshd service and check the status
Lastly I hope the steps from the article to disconnect idle SSH session, ssh close connection after sometime or to avoid idle SSH session getting disconnected on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
Источник
How to kill or disconnect hung ssh session in Linux
Table of Contents
How to disconnect hung ssh session in Linux. disconnect stuck ssh session in Unix, Terminate stuck ssh session. kill an unresponsive ssh session in Unix. Kill stuck ssh session. Terminate stuck ssh session in Linux. kill ssh session in Linux. Close ssh connection. Terminate an unresponsive ssh session in LInux. Automatically kill or disconnect hung ssh session using ServerAliveInterval. Automatically kill a PSSH session using timeout in Linux. Disconnect hung pssh session in linux after certain time period. Kill stuck ssh session automatically in Linux. Automatically disconnect hung ssh session in Unix.
In this article we will cover various examples around the topic to kill stuck ssh session i.e to disconnect hung ssh session in Linux, but if you wish to automatically disconnect an idle session then I have written another article wherein I have shared the steps and examples to automatically disconnect an idle ssh session in Linux.
What is an unresponsive SSH session?
By unresponsive SSH session we mean that a SSH connection is not responding or has become unresponsive between the host and the client. This situation can arise due to various reason, most likely due to network fluctuations between the server and the client. You can list all the active SSH connections and then check the idle time to get their current status. You can also get their PID from the remote host to manually kill the unresponsive ssh session.
Terminate stuck ssh session
There is a «secret» keyboard shortcut to force an unresponsive ssh session to exit.
From the frozen session terminal, hit these keys in order: Enter →
→ . The tilde (only after a newline) is recognised as an escape sequence by the ssh client, and the period tells the client to terminate it’s business without further ado.
From the man page of SSH
Here I have created an active session from node1 to node2 using user ‘ deepak ‘. Now this session is in hung state.
Here i have pressed » Enter » followed by
and . (dot) will be hidden and will not be visible on the screen. But after finishing this sequence, the session will be immediately terminated.
As you see my hung session is terminated and I have returned back to my localhost.
→ . will get you back to your local session, Enter →
→ . will leave you in Machine1, and Enter →
→ . will leave you in Machine2. This works for other escape sequences as well, such as moving the ssh session to background temporarily. The above works for any level of nesting, by just adding more tilde’s.
For example:
Here I have made an active SSH session from node1 to node2 and from node2 to node3 i.e. node1 → node2 → node3
Now here I will disconnect stuck SSH session from node3 to node2 instead of node1. So I will hit Enter →
Automatically disconnect hung SSH session
Now in the above example you were manually terminating the stuck ssh session, but to automatically disconnect hung SSH session or when you are automating a task and your SSH process gets stuck, in such cases it is better if the SSH itself disconnect hung SSH session itself rather than someone manually intervening and killing the process.
In this case you can use » ServerAliveInterval » to automatically disconnect the hung SSH session.
From the man page:
So using ServerAliveInterval you can set a timeout value which will be used if the provided SSH session becomes unresponsive. You can use this either via command line or by creating a ssh_config file inside the respective user’s home directory.
Method 1:
While initiating a SSH connection use » -o ServerAliveInterval=XX » along with the SSH command. here replace » XX » with your suitable timeout value.
For example:
I am running a SSH session from node1 to node2, and will disconnect the NIC interface. Now this is not the best scenario to have a hung session but this will do the trick to explain our steps and example. Now here I have provided an interval of 5 seconds and TCP packet will be sent two times before disconnecting the session.
From the debug logs printed on the screen, there are two debug packets which are sent before disconnecting the session
Now here as expected my session my session was automatically disconnected after sending 2 TCP packets at an interval of 5 seconds.
Method 2:
You can configure these values per user by creating a new file ssh_config inside user’s home directory. For example if my user’s home directory is /home/deepak/ then create following file
Add below content
Here * is used to refer for any matching host. If you wish to restrict it for a certain host then provide the IP/hostname.
Method 3:
Lastly you can update /etc/ssh/ssh_config and add the same values. This was the configuration will not be at user level instead it will be at system level
Add below content
Use timeout to kill SSH session
You can additionally use timeout command to disconnect hung SSH session. To define a timeout value for the active session.
Here the benefit is that if for automation you are using ssh command and you do not wish the automation script to get stuck during execution then you can use timeout command to kill the session after certain period of time.
From the man page of timeout:
For example:
I have created a script to trap SIGTERM and capture the progress of timeout
Adding the -k 12 switch tells timeout to send a SIGKILL to the process 12 seconds after the initial SIGTERM. Again, the » SIGTERM received » message is displayed after 3 seconds as a result of the SIGTERM signal. Twelve seconds after that, the whole script is killed. It does not complete the second 20-second sleep, and it does not display the Finished message after it. This is a more forceful way of dealing with the timeout.
Similarly you can utilise timeout with SSH command. Assuming you know that your SSH command execution will take 10 seconds then you can define a timeout of 20 seconds as the hard period for killing the session
Disconnect PSSH session
PSSH is another tool to perform SSH (parallel) instead of sequential. Now in PSSH there is an internal argument which can be used to kill the active session after a certain time period. You need not be dependent on any additional tool to disconnect the SSH session.
From the man page of pssh:
For example:
Execute pssh using below syntax to perform a timeout automatically after 30 seconds
So as expected the PSSH session was automatically killed with the timeout signal after the provided timeout value.
Lastly I hope the steps from the article to disconnect hung SSH session or unresponsive SSH session on Linux was helpful. So, let me know your suggestions and feedback using the comment section.
Related Posts
Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud
If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.
For any other feedbacks or questions you can either use the comments section or contact me form.
Thank You for your support!!
2 thoughts on “How to kill or disconnect hung ssh session in Linux”
the only article I found on google (not internet, but google 🙂 )
which correctly describes how to kill a very long SSH session by setting/defining hard limits.
I’ve been in this business for quite a while and have always been annoyed about not knowing how to kill only one nested ssh session and not the whole chain. I’m happy I ran across your page!
Источник