Often I find myself working with multiple remote SSH sessions. Keeping track of which session belongs to which server is tough enough but when a script takes longer than expected or I have to disconnect before it completes adds another layer of complexity. Luckily the Free Software community has something called “Screen”. It’s a great utility where programs or processes continue to run when their window is currently not visible and even when the whole screen session is detached from the users terminal. In other words my session will happily continue even after I terminate my SSH connection. Best of all, it will be there waiting for me when I’m ready to reconnect.
Using Screen is super easy. After connecting to your remote host (typically through SSH) activate screen with the following command.
At this point continue your administrative tasks as usual. If you ever have to disconnect for any reason but have a need to preserve your session while disconnected issue the following keystrokes;
<CTRL> A followed by the letter ‘d’
(<CTRL A> grabs screen’s attention and ‘d’ detaches terminal)
At this point you may safely terminate your SSH connection because your programs and scripts will continue running.
When you’re ready to come back, simply re-establish an SSH connection and through Screen Magic reattach your session. Everything including any running scripts are right where you left them.
(This will list all detached screens by PID ‘process id’)
There are screen on:
3190.pts-0.hostname (09/02/11 11:48:59 AM) (Detached)
1854.pts-1.hostname (05/02/11 01:33:44 PM) (Detached)
Where ‘3190’ and ‘1854’ are processes i.e. (PID)
#screen –r PID
(This will reattach specified screen)
I have found screen to be very useful when multi-tasking between servers. It doesn’t happen very often but from time to time I’ve had to disconnect in the middle of something and screen has been there for me every time.