Как разорвать ssh соединение linux
Перейти к содержимому

Как разорвать ssh соединение linux

  • автор:

Sorry, you have been blocked

This website is using a security service to protect itself from online attacks. The action you just performed triggered the security solution. There are several actions that could trigger this block including submitting a certain word or phrase, a SQL command or malformed data.

What can I do to resolve this?

You can email the site owner to let them know you were blocked. Please include what you were doing when this page came up and the Cloudflare Ray ID found at the bottom of this page.

Cloudflare Ray ID: 7d99c9b69f94787b • Your IP: Click to reveal 138.199.34.39 • Performance & security by Cloudflare

How do I exit an SSH connection?

I’m connecting to a server via SSH to send a message to a socket server using a command like:

After the connection is established and I write the message and send it I can’t exit the text mode. I’m only allowed to enter more text and that’s it.

Is there a command or a key combination that allows me to return to command mode?

DavidPostill's user avatar

7 Answers 7

How do I exit an SSH connection?

  • closing the shell session will usually exit, for example:
    • with the shell builtin command, exit , followed by Enter , or
    • Ctrl — d , (end-of-file)

    The first option should be intuitive, but how do we know the latter option?

    We could learn this information from a careful reading of the man page.

    gives us the SSH documentation, which has the following section on escape characters:

    There is nothing special about exit to ssh, it’s just a way to exit the shell, which results in closing the ssh session:

    Citing and quoting reference sources is to provide further evidence for what would otherwise be a perhaps demonstrable assertion of fact, as well as inform the user where more relevant information may be stored.

    You want to know that you’re doing semantically the correct thing, as well as knowing that it works.

    You don’t want to learn to invoke as a feature something that is documented as a bug and then later "fixed." Doing the semantically correct thing will continue to be supported.

    How to kill or disconnect hung ssh session in Linux

    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.

    How to kill or disconnect hung ssh session in Linux

    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.

    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.

    Buy GoLinuxCloud a Coffee

    For any other feedbacks or questions you can either use the comments section or contact me form.

    Thank You for your support!!

    4 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!

    This is a great. I was always annoyed with hung ssh sessions and had to kill them using ps -a, kill and other tricks. This article explains the solution perfectly and I am saved from performing so many not so comfortable actions just in order to get rid of a hung ssh session.

    This article is worthy of recognition and comment. I found this material attention-grabbing and engrossing. This is well-scripted and highly informative.

    �� Команда Linux для выхода из SSH-соединения

    Мануал

    Когда речь идет об управлении удаленными системами в Linux, протокол SSH является наиболее используемым методом.

    SSH популярен, потому что позволяет пользователю безопасно входить в удаленные устройства, включая другие системы Linux, брандмауэры, маршрутизаторы и т.д.

    Когда вы закончите удаленное управление, вы должны выйти из SSH-соединения.

    В этом руководстве вы узнаете о командах, которые можно использовать для выхода из SSH-соединения в Linux.

    Вы также узнаете, какие символы используются для выхода из сеанса SSH, что может пригодиться, если вы столкнулись с зависанием системы, к которой подключены по SSH, и вам нужно вернуться в локальный терминал.

    Команда Linux для выхода из сеанса SSH – Все способы

    Существует множество команд Linux, которые можно использовать для выхода из соединения SSH.

    Ознакомьтесь с различными методами ниже:

    Типичным способом выхода из SSH-соединения является использование команды exit.

    Эта команда работает для отключения от систем Linux, а также множества других устройств и операционных систем.

    Большинство администраторов используют именно этот метод.

    Второй способ выйти из сеанса SSH – это команда logout.

    Это сработает на системах Linux, но может не сработать на других устройствах с другими операционными системами.

    Но обычно это срабатывает.

    Если вы относитесь к тем пользователям, которые любят сочетания клавиш и максимальную эффективность, вам может понравиться сочетание клавиш Ctrl + D, которое выполняет команду завершения файла.

    Это позволит мгновенно завершить сеанс SSH.

    Если ваше SSH-соединение заморожено, три описанных выше метода могут не сработать.

    В этом случае вы можете набрать

    . чтобы выйти из сеанса SSH и вернуться в локальный терминал командной строки.

    Этот символ работает как символ выхода для SSH-соединений.

    Заключение

    В этом уроке мы рассмотрели, как выйти из сеанса SSH в системе Linux.

    SSH является важным инструментом для удаленного администрирования, поэтому знание того, как выйти из сеанса, будет необходимо всякий раз, когда вы будете готовы прервать соединение.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *