131

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?

2

3 Answers 3

180

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.

3
  • 28
    Actually 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). Oct 9, 2010 at 0:04
  • 6
    In (at least) Portuguese keyboards double tap ~ and then .
    – rsilva4
    Mar 11, 2013 at 21:10
  • 1
    I was trying to ~^C, not understanding where to place the <kbd>Enter</kbd>, but ~. (as . apparently means to quit) followed by enter did the trick.
    – mazunki
    May 15, 2020 at 21:56
23

Just to clarify, hope this helps newcomer.

  1. Press Enter

  2. Press ~ (this is shift + ` on a keyboard with US layout)

  3. Press .

Cursor will return to local prompt.

2
1

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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .