Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reconnect to accidentally disconnected ssh session WITHOUT screen or tmux

I know these kinds of questions have been asked for years, and the answer to them are often Screen or tmux.

I surely will use screen at beginning if I know I will leave the session for a long time, or the network is too bad to maintain a reliable connection.

The main problem is when I start some session and find it must last long later, or the connection just lost accidentally. In the later case, often when I start another session immediately, I can find the previous processes are not killed at that time, but I just have no way to reconnect to their terminal.

So I wonder if it is possible to prevent normal processes from killed even long time after accidentally disconnected SSH session. And the most important is I can reconnect to their terminals with out start them in Screen in advance.

If not, is is possible to move a already started bare ssh session into a new Screen session for later reconnect?

like image 418
lyu Avatar asked Nov 22 '13 02:11

lyu


1 Answers

I don't believe it's possible without something like screen. Once your pseudo-TTY is lost I'm almost certain it can't be recovered from a different shell (at least not without some narly hacks).

As far as adding an existing process to a new screen I think that is possible. Try the instructions here:

http://monkeypatch.me/blog/move-a-running-process-to-a-new-screen-shell.html

The first thing to do is to suspend the process. In my case, Irssi can be suspended by typing Ctrl + Z.

Secondly, resume the process in background:

$ bg

Now, we will detach the process from its parent (the shell). So, when the parent process will be terminated, the child (Irssi) will be able to continue. For this, we use the disown builtin:

$ disown irssi

Launch a screen session:

$ screen

As we are in a screen session, we will retrieve the irssi process. To do so, we use the reptyr command which take a pid:

$ reptyr

To avoid the tedious pid research, we can use the pgrep command:

$ reptyr $(pgrep irssi)

Now the process is in a screen shell, we can safely detach our session and no longer worry about killing our X server or close our ssh connection.

You'll need reptyr for this.

OPTION 2:

I suspect you may be trying to solve the wrong problem. If your SSH connection is dropping, why not address that? You can set SSH to be incredibly tolerant of timeouts and disconnects by tweaking your connection settings.

On your client, in $HOME/.ssh/config add:

ServerAliveInterval 60
ServerAliveCountMax 5

Now your sessions won't timeout even if the server doesn't respond for 5 minutes.

like image 124
SpliFF Avatar answered Oct 10 '22 17:10

SpliFF