Monday, September 16, 2013

Remote SSH sessions: screen

This is one of the most usefull things I have come across: when working via SSH/telnet on remote hosts, you can get disconnected for any reason: timeouts, connection drops, etc. You may have been in the middle of running a script, and now you won't know if the script finished. You can use 'screen' to overcome and simply reconnect where you left of. 

This link says it better:

Even tho this is not a direct answer to your question, it is highly related to the problem you have. Instead of trying to keep the connection alive (all connections eventually die) you can use terminal multiplexors, like screen and tmux that keep the session alive in the background even if your terminal gets disconnected.
Essentially when you login in to the SSH server you immediately run screen which will create and attach a new session:
$ screen
Then you go ahead and do your work with the shell as you would normally do. Now if the connection gets dropped, when you can get back online and reconnect to the server over SSH, you get a list the current sessions with:
$ screen -ls
To reattach to a session:
$ screen -r <session>
where <session> is the PID or a session name. You will be reconnected to your session and you can continue from where you left off!
You can even detach the session and reconnect from home to pick up from the exact point where you left off. To detach the session you use C-a followed by C-d (thats Control + A and then Control + D).
There is simple online tutorial as well.
Using screen and tmux on remote servers is considered a best practice and is highly recommended. Some people go as far as to have screen as their default login shell, so when they connect they immediately start a new screen session.

Now if you dont want to have to remember to  screen when you login to a remote box, you can automate it with these scripts:

I'm still playing around with it to see if it works for me.

Post a Comment