Friday, July 29, 2022

[SOLVED] SSH connection keeps hanging up in terminal

Issue

This is an issue that keeps bothering me for one year!!!

I need to ssh into my remote servers both at the office and at home frequently. Usually, it works well at the office. But when at home, the ssh connection drops(or hang up) quickly. Sometimes when I come back two or five minutes, the ssh session is dead and Ctrl+c, Ctrl+z and Ctrl+d takes no effect.


Solution

Here are two problems:

  1. SSH session hangs up and not easy to close it.

Cause: Normal keys are forwarded over the ssh sessions so they have no effect now.

Solution: We can use the escape key sequence(Enter ~ .) to close it. In the hang-up terminal hit Enter ~ ? subsequently, it will show you a list of supported escape sequences like this:

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.)
  1. SSH session hangs up in a short period.

Cause: It may depend on your network type and your router. the enterprise router is more powerful than the home router to keep the long live connection. At home, We may have only one IP address from the ISP and many devices. Usually, in order to handle multiple devices with one external IP address, the home router will create a NAT network(WIFI) and assign an internal IP address for each device. When your devices send requests and receive responses from the internet, the home router needs to maintain a connection mapping table to make all the connections work perfectly. But the connection mapping table is very small, when it has no more capacity, it will drop some connections which considered dead to let the new connection to join.

Solution: In the SSH version 2, there is a "No Operation" message type(NOOP) which can be used to keep ssh session live. Add the following config in your ssh config which located at ~/.ssh/config by default.

Host *
  ServerAliveInterval 300

The number 300 can be adjusted according to your router.

Hope this can help others.

Does anyone have any other suggestions? Correct me if my understanding is wrong.



Answered By - Max Peng
Answer Checked By - David Marino (WPSolving Volunteer)