How to close a frozen remote ssh connection

28 Nov 2021

Breaking out of SSH

We’ve all been there. You are working on your remote server though ssh, and suddenly a colleague restart openvpn, or your ISP crapy modem restart… You end up with a frozen ssh prompt, and no ctrl+c or ctrl+d give let you break that.

If you aren’t too familiar with this issue, you probably don’t know how to fix this, and quickly end up closing the terminal and opening another one. This work but there is a “better” way.

Closing the session

One of the little secret of ssh are its escape sequences. You’ll get to learn them when you do a lot of it, but without reading the man page, or some Stack Exchange board, you won’t just figure it out.

The ~ is the key of it all but in order for it to be recognized, you need to type it immediately after a new line. In order to show the list of available escape sequences, here is what to press, one at a time: <enter> ~ ?

Supported escape sequences:
 ~.   - terminate connection (and any multiplexed sessions)
 ~B   - send a BREAK to the remote system
 ~C   - open a command line
 ~R   - request rekey
 ~V/v - decrease/increase verbosity (LogLevel)
 ~^Z  - suspend ssh
 ~#   - list forwarded connections
 ~&   - background ssh (when waiting for connections to terminate)
 ~?   - this message
 ~~   - send the escape character by typing it twice

There is a lot in here, but what matter to you right now is the first one, <enter> ~ .. This will terminate the hanging connection and let you restart it.

Feel free to try and learn about the other one but keep in mind that some command need the client to be compatible.

What about bounced/bastion connection ?

So you or your office have a bastion of some sort ? A server you ssh into in order to ssh again on other server ? That’s a very good idea ! But if the session that freeze isn’t the one between you and the bastion, but between the bastion and the remote… what can you do ? Sadly, sending <enter> ~ . will only kill your side of the connection, and if you are like me, you have a tmux or a screen running on the bastion to keep it all neat and organized. This just don’t solve anything.

Happily there is also a trick for that, and it’s the last one of the escape sequences, ~~. By doubling it, you are actually sending the character downstream. So closing a 1 bounce stream is a simple as <enter> ~ ~ ..


This isn’t new for anyone, and internet is full of post asking this exact question with the same exact reply. But I still wanted to make one because of that second part. I often rollback snapshot of vm and doing so break the ssh connection. Until now, because I was using tmux on a bounce server, I had to kill the pane and open a new one.

Since I found out I could also kill remote session, it made it less painful, so I thought it was a good thing to share.

Hope you learned something :)