Sometimes my ssh session in the terminal hangs. How can I exit the ssh session and reconnect?
~. (i.e. tilde, period) at the beginning of a line. In other words, press Enter, then ~, then .. (In some languages, you may need to press Shift or Alt to enter the
Generally speaking, the
~ character is an escape character in an SSH session when you type it at the beginning of a line. Type Enter then
~? to see the list of escape commands. The most common ones are
~.to terminate the connection
~^Z(press ~ then Ctrl+Z) to suspend the connection and type a command locally (run the command
fgto return to the SSH session)
If you want a tilde at the beginning of a line, press ~ twice.
If your session is hung and the prompt is no longer responsive you can just kill the Terminal instance and all child processes associated with that instance, of which your ssh session is one, should get axed along with it.
If you're really wanting to be thorough though you can open a new Terminal instance, look for ssh sessions in the process list, and kill them via the command line:
> ps -ef |grep ssh 501 1332 142 0 20Dec11 ?? 0:01.33 /usr/bin/ssh-agent -l 501 57172 57150 0 1:58pm ttys000 0:00.01 grep ssh 501 57139 57133 0 1:57pm ttys002 0:00.03 ssh -i/Users/ian/code/ec2-keys/id_rsa-gsg-keypair email@example.com > kill 57139
If that doesn't work try:
> kill -9 57139
Don't kill the
Or you can open Activity Monitor and search there for sessions and hit the kill button for them:
According to the documentation:
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 (Note that escapes are only recognized immediately after newline.)
For me, working with Terminal in macOS Mojave 10.14.6 the only solution was to enter ~ followed by Ctrl-Z as described in this answer: https://apple.stackexchange.com/a/175670/136875