How can I break away from an SSH session that has crashed?

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 tmux or 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?

Answers:

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.

Method 1

Use the “escape character” (normally, the tilde ~) to control an SSH session:

  • ~ followed by . 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
ssh.

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.)

Method 2

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 ClientAliveInterval and ClientAliveCountMax config options. From the client side, see the ServerAliveInterval and ServerAliveCountMax options. 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.

See the OpenSSH sshd config man page and the OpenSSH ssh config man page for further infrormation.

Method 3

Try Ctrl+Break


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x