5

I"m using Mac 10.9.5 with bash shell. Occasionally when I ssh into another machine and then the connection dies (e.g. the Internet goes down or I move to a new location), the terminal window with the open SSH session is frozen and the only way I seem to be able to move ahead is to close it and start a new session.

Is there some way to configure things such that if the SSH session's connection dies, I will be returned back to my normal bash shell, as it was before I executed my SSH command?

  • Try configuring ServerAliveCountMax and ServerAliveInterval in your ~/.ssh/ssh_config. – Scott Dudley Mar 11 '15 at 1:51
  • @ScottDudley can you provide more details? – phatmann Feb 11 '16 at 18:40
  • @phatmann eg. with ServerAliveCountMax 4 and ServerAliveInterval 15, if the SSH client does not receive a response from the server after 4*15=60 seconds, it should disconnect automatically. See the man page for more details. – Scott Dudley Feb 12 '16 at 2:03
  • return then ~. more info apple.stackexchange.com/questions/35524/… – clarkttfu Jan 22 at 7:55
6

You can suspend and then kill the ssh process that's hung up. To do this you have to issue the escape sequence, suspend the ssh process, and then use kill -9 to kill that process.

The default escape key for the ssh that ships with OS X the ~ character. You have to enter it immediately after a new line for ssh to respect it. And then the key sequence Control-z is used to suspend and background a task in bash.

So try this key sequence:

Return

~

Control-z

If it works you'll see something like:

myhost.local:~ |ruby-2.2.0|
> ssh someremotehost
Last login: Fri Mar  6 14:15:28 2015 from myhost

someremotehost:~ |ruby-2.2.0|
> ~^Z [suspend ssh]

[1]  + 48895 suspended  ssh myremotehost

This line of output:

[1]  + 48895 suspended  ssh myremotehost

tell you the process ID of the ssh process on your machine. It's 48895 in this example. That process is still running, it's just been suspended and backgrounded. You need to kill it.

You can do that with the kill command. You want to kill it with prejudice so use the -9 option when you call kill like so:

myhost.local:~ |ruby-2.2.0|
> kill -9 48895
[1]  + 48895 killed     ssh someremotehost

Just use the PID of your ssh process when you call that command in place of the 48895 PID I used above.

And you'll have your prompt back.

Alternatively, you can open a second Terminal window and use ps to find the ssh process in the process list and issue the kill -9 call against the PID. Though, that kind of defeats the process of getting your prompt back in the original Terminal window, doesn't it?

You must log in to answer this question.

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