Is there a way to disconnect from an SSH session that has become unresponsive without killing the whole terminal? Specifically I'm using konsole, and the machine I'm working with sometimes hangs, but doesn't actually die (thus killing the connection). So SSH just hangs and I have to close the terminal and open a new one to try to ssh back into it or do anything else. Is there a way to effectively ctrl+c out of an ssh session?
-
2Do read this: What can I do when my SSH session is stuck? – Shubham Sep 29 '18 at 19:48
-
Related question: How can I keep my SSH sessions from freezing? - Unix & Linux Stack Exchange – user202729 Dec 02 '23 at 23:46
3 Answers
One way is to use the ssh escape character. By default this is "~", but it can be set manually with -e
option when invoking ssh or via EscapeChar
in your ssh config. To kill the hung session this will often work:
~.
As pointed out by Gilles this is only recognized immediately after hitting Enter.

- 46,160
-
28Actually this will work regardless of what is happening on the remote machine. What you've experienced is that
~
is only active immediately after you've pressed Enter (otherwise it would be too intrusive). – Gilles 'SO- stop being evil' Oct 09 '10 at 00:04 -
6
-
1I was trying to
~^C
, not understanding where to place the Enter, but~.
(as.
apparently means to quit) followed by enter did the trick. – mazunki May 15 '20 at 21:56 -
@rsilva4 you probably have deadkeys. that is, you graphical interface have something that intercepts accents chars, hold them without forwarding to the application, until you press another letter to send the accented vowel. If you press the accent twice, it sends the accent alone. That's why you have to press
~~
to get~
. Ssh doesn't know about any of this. – gcb Dec 23 '23 at 22:23
Just to clarify, hope this helps newcomer.
Press Enter
Press ~ (this is shift + ` on a keyboard with US layout)
Press .
Cursor will return to local prompt.

- 1,637
- 14
- 17

- 611
-
1
-
1@lucidbrot see Gilles' comment at https://unix.stackexchange.com/questions/2919/kill-an-unresponsive-ssh-session-without-closing-the-terminal#comment3080_2920; you wouldn't want
~
being interpreted in the middle of UNIX command-line, for example. – Jeff Schaller Jun 12 '23 at 15:34
If you ever want to terminate all active ssh sessions you can use this command (assuming that only ssh is connected to port 22):
kill `sudo lsof -Pni :22 | tail -n1 | grep -wv sshd | awk '{print $2}'`
This command finds all processes connected on port 22, removes the banner of lsof
command output, ignores the ssh daemon process and gets all the PIDs, then terminates those PIDs.

- 125