SSH Escape Sequences: How to Terminate and Control SSH Sessions
Understanding SSH Escape Sequences
When connected to a remote server via SSH, normal keyboard input is forwarded directly to the remote system. This creates a challenge if you need to control the SSH connection itself rather than sending commands to the remote server.
SSH solves this problem with escape sequences - special key combinations that are intercepted by the SSH client rather than being sent to the remote server.
Terminating a Stuck SSH Session
To immediately terminate the current SSH session (especially useful when a session is frozen):
- Press
Enter(to ensure you’re at the beginning of a line) - Press
~(tilde) - Press
.(period)
This key sequence (Enter → ~ → .) will immediately close the connection.
Available Escape Sequences
To view all available escape sequences during an active SSH session:
- Press
Enter - Press
~ - Press
?
~. - terminate session
~B - send a BREAK to the remote system
~R - Request rekey (SSH protocol 2 only)
~# - list forwarded connections
~? - this message
~~ - send the escape character by typing it twice
Important Notes About Escape Sequences
- Timing matters: Escape sequences are only recognized immediately after pressing Enter (at the beginning of a new line)
- After viewing the list of escape sequences, press Enter to return to your session
Working with Nested SSH Sessions
When you have multiple SSH sessions nested inside each other (connecting from one server to another), you can target specific connection levels:
- Because typing
~~sends a literal~to the remote system, you can use multiple tildes to target nested connections - The number of tildes corresponds to the depth of the connection you want to target
- For example, to terminate the fifth-level SSH connection while keeping the other four intact, type:
Enter→~~~~.
Reference
This information is adapted from this AskUbuntu answer.