Kill an unresponsive ssh session without closing the terminal

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?

Asked By: Falmarri

||

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.

Answered By: Steven D

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.

Answered By: Brain90

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.

Answered By: Human
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.