Using SSH with Screen for Session Management

Customize your ~/.screenrc

source: http://magazine.redhat.com/2007/09/27/a-guide-to-gnu-screen/

This will make a nice UI showing you at the bottom which screen you're using plus other things.

# vi ~/.screenrc

paste this in:

hardstatus alwayslastline
hardstatus string '%{= kG}[ %{G}%H %{g}][%= %{= kw}%?%-Lw%?%{r}(%{W}%n*%f %t%?(%u)%?%{r})%{w}%?%+Lw%?%?%= %{g}][%{B} %Y-%m-%d %{W}%c %{g}'
# Default screens
screen -t shell1        0
screen -t shell2        1
screen -t server        2

After you can switch between screens by: CTRL-A + N

common commands:

connect to an existing session in use (attached) and detach whomever is connected:

# screen -ls

There is a screen on:
        9231.pts-2.srv3 (Attached)
1 Socket in /var/run/screen/S-root.

# screen -d -r 9231.pts-2.srv3
(this last command (-d) will allow you to take over a session even if it's attached)

connect to an existing session (attached) to view it without disconnecting others:
# screen -x 9231.pts-2.srv3

All commands

Use: screen [-opts] [cmd [args]]
 or: screen -r [host.tty]

Options:
-a            Force all capabilities into each window's termcap.
-A -[r|R]     Adapt all windows to the new display width & height.
-c file       Read configuration file instead of '.screenrc'.
-d (-r)       Detach the elsewhere running screen (and reattach here).
-dmS name     Start as daemon: Screen session in detached mode.
-D (-r)       Detach and logout remote (and reattach here).
-D -RR        Do whatever is needed to get a screen session.
-e xy         Change command characters.
-f            Flow control on, -fn = off, -fa = auto.
-h lines      Set the size of the scrollback history buffer.
-i            Interrupt output sooner when flow control is on.
-l            Login mode on (update /var/run/utmp), -ln = off.
-list         or -ls. Do nothing, just list our SockDir.
-L            Turn on output logging.
-m            ignore $STY variable, do create a new screen session.
-O            Choose optimal output rather than exact vt100 emulation.
-p window     Preselect the named window if it exists.
-q            Quiet startup. Exits with non-zero return code if unsuccessful.
-r            Reattach to a detached screen process.
-R            Reattach if possible, otherwise start a new session.
-s shell      Shell to execute rather than $SHELL.
-S sockname   Name this session .sockname instead of ...
-t title      Set title. (window's name).
-T term       Use term as $TERM for windows, rather than "screen".
-U            Tell screen to use UTF-8 encoding.
-v            Print "Screen version 4.00.03 (FAU) 23-Oct-06".
-wipe         Do nothing, just clean up SockDir.
-x            Attach to a not detached screen. (Multi display mode).
-X            Execute  as a screen command in the specified session.

source: http://www.freepbx.org/book/export/html/5252

(Never have your upgrade/installation die because you lost your connection!)

Using Screen for Session Mgmt (Never have your upgrade/installation die because you lost your connection!)

Ever had a remote SSH connection where you were doing an upgrade (say to asterisk or pbxinaflash, etc) and you lost your internet connection, which killed your ssh session, and stopped your compile, leaving your system in a horribly unusable state? NEVER AGAIN! That is what I use screen for!

This will quickly become your FAVORITE AND REGULARLY USED LINUX UTILITY!!!

What is Screen?
As the man page states, "Screen is a full-screen window manager that multiplexes a physical terminal between several processes (typically interactive shells)." This can be a life saver when working with remote servers. Screen has a several great features for helping you administer your linux box more productively and most importanly, safely.

I am going to discuss the four features (multiple windows, sessions, logging, sharing) that I use the most.
(Check out the man screen for more info)

Installing Screen
If you are using a RedHat/CentOS distribution, you probably already have this installed (pbxinaflash/trixbox/and more!) You will find it in /usr/bin/screen. To see if it is, type which screen
If you do not have it already installed, it is easily installed by doing "yum install screen" or installing the appropriate RPM for your distribution (most distributions have this great application, and it's been around for YEARS). You can visit the screen website at http://www.gnu.org/software/screen/

Using Screen
Screen is started from the command line, just like any other application

[root@pbx ~]# screen
You may or may not get a text message about screen. If you do not, then you probably think nothing has happened, but it has. You are now inside of a window within screen. This functions just like a normal shell except for a few special characters. Screen uses the command "Ctrl-A" as a signal to send commands to screen instead of the shell. To get help, just use "Ctrl-A" then "?". You should now have the screen help page.

                               Screen key bindings, page 1 of 2.

                               Command key:  ^A   Literal ^A:  a

 break      ^B b        info       i           other      ^A          suspend    ^Z z
 clear      C           kill       K           pow_break  B           time       ^T t
 colon      :           lastmsg    ^M m        pow_detach D           title      A
 copy       ^[ [        license    ,           prev       ^P p ^?     vbell      ^G
 detach     ^D d        lockscreen X           readbuf    
 focus      ^I          next       ^@ ^N sp n  select     '           xoff       ^S s
 help       ?           number     N           silence    _           xon        ^Q q
 history    { }         only       Q           split      S
                          [Press Space for next page; Return to end.]

Key bindings are the commands the screen accepts after you hit "Ctrl-A". You can reconfigure these keys to your liking using a .screenrc file, but I just use the defaults.

Multiple Windows
Screen, like many windows managers, can support multiple windows. This is very useful for doing many things at the same time without opening new sessions. As a RHCE, I often have four or five SSH sessions going at the same time. In each of the shell, I may be running two or three applications. Without screen, that would require 15 SSH sessions, logins, windows, etc. With screen, each system gets its own single session and I use screen to manage different tasks on that system.

To open a new window, you just use "Ctrl-A" "c". This will create a new window for you with your default prompt. For example, I can be running top and then open a new window to do other things. Top stays running! It is still there. To try this for yourself, start up screen and then run top.
start "top"
Now open a new window with "Ctrl-A" "c"
To get back to top, use "Ctrl-A "n"

You can create several windows and toggle through them with "Ctrl-A" "n" for the next window or "Ctrl-A" "p" for the previous window. Each process will keep running while your work elsewhere.

Leaving Screen
There are two ways to get out of screen. The first is just like logging out of a shell. You kill the window with "Ctrl-A" "K" or "exit" will work on some systems. This will kill the current windows. If you have other windows, you will drop into one of those. If this is the last window, then you will exit screen.

The second way to leave screen is to detach from a windows. This method leaves the process running and simple closes the window. If you have really long processes, you need to close your SSH program, you can detach from the window using "Ctrl-A" "d". This will drop you into your shell. All screen windows are still there and you can re-attach to them later.

Re-attaching to existing sessions
This is the best part!!

So you are using screen now and compiling a program. It is taking forever and suddenly your connection drops. Don't worry screen will keep the compilation going. Login to your system and use the screen listing tool to see what sessions are running:

[root@pbx ~]# screen -ls
There are screens on:
31620.pts-0.pbx (Detached)
31625.pts-0.pbx (Detached)
2 Sockets in /var/run/screen/S-root.

Here you see I have two different screen sessions. To re-attach to a session, use the re-attach command:
[root@pbx ~]#screen -r 31620.pts-0.pbx
Just use screen with the -r flag and the session name. You are now re-attached to the screen. A nice thing about this, is you can re-attach from anywhere. If you are at work or a clients office, you can use screen to start a job and then logout. When you get back to your office or home, you can login and get back to work. If you only have one screen running, screen -r will automatically connect to that session.

Screen Logging
I find it important to keep track of what I do to someone else's server. Fortunately, screen makes this easy. Using "Ctrl-A" "H", creates a running log of the session. Screen will keep appending data to the file through multiple sessions. Using the log function is very useful for capturing what you have done, especially if you are making a lot of changes. If something goes awry, you can look back through your logs.

Sharing a Screen Session
If you have two users connected to the same server (say as root) and one user types screen another user can type screen -x and now BOTH of you are able to type and view in the same window!!! GREAT FOR REMOTE TRAINING OR GETTING ASSISTANCE FROM SOMEONE ELSE, especially if you want to know how they fixed your server!!

Screen Tips
I also wanted to mention to other beneficial tricks you can do with screen. Screen can monitor a window for activity or lack thereof. This is great if you are downloading large files, compiling, or watching for output. If you are downloading something or compiling, you can watch for silence. To start the monitor, go to the screen you want to monitor and use "Ctrl-A" "M" to look for activity or "Ctrl-A" "_" to monitor for silence. Then open or switch to a new window. When the monitor detects activity or silence, you will get an alert at the bottom with the window number. To quickly go to that window, use "Ctrl-A" " (thats a quote mark, ctrl-a then a "). After you do this, just type in the number of the window and enter. To stop monitoring, go to that window and undo the monitor with the same command. For example, to stop monitoring for activity you would use "Ctrl-A" "M" again.

Hopefully this will help.. well lets face it, ALL OF US... in working with remote servers and help to ensure we don't brick the server while we work remotely!

Richard Teachout
RHCE, MCSA, MCTS:Hosting