Many times I have an SSH session that doesn’t respond anymore (for example, when I lose internet connection and then reconnect). Ctrl+C, Ctrl+D, Ctrl+Z and a zillion of key presses don’t have any effect.
Most of the time I already have
byobu running already, so I can just start another terminal and reconnect. However it does feel cumbersome. How can I disconnect SSH from the current terminal?
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Use the “escape character” (normally, the tilde
~) to control an SSH session:
.closes the SSH connection;
~followed by Ctrl+Z suspends the SSH process;
~followed by another
~sends a literal
You can set the escape character using the
-e option to
Additionally, remember that
You should also remember to press Enter before ~. The escape character works when it is the first character in the line. And also you can use ~ and later ? to get help from the ssh client. (Thanks to the comment by Lukasz Stelmach.)
Openssh can be configured to send client or server alive messages to the other side. If no response is obtained, the connection will be terminated. From the server side, see the
ClientAliveCountMax config options. From the client side, see the
TCPKeepAlive is also an option, but is spoofable while the former options aren’t, so they are probably better.
If you set these to reasonable values, you’ll probably never have a connection hang again. The only downside is that your ssh connections might stay open if you would rather they would terminate, for security reasons.