Using
Screen
Robert Bernier
Successful remote administration is a bit of an art form, but
you don't need cutting edge technology to do it right. The key lies
in using the right tools for the job at hand.
Screen is a console manager with VT100/ANSI terminal emulation.
In other words, it is a console-based window manager that creates
virtual windows, which is known as multiplexing. Screen lends itself
well to an ever-changing and unpredictable work environment. For
example, screen allows you to run multiple terminal sessions off
just one login, see multiple windows on the same console, keep a
session active even after you've logged off, transfer control of
your sessions from one machine to another, and keep a hardcopy of
your sessions, to name just a few. In this article, I'll go through
the mechanics of setting up and using screen.
Getting Screen
You can get screen either as a binary for your particular operating
system, or you can download the source code from its main development
site at:
ftp://ftp.uni-erlangen.de/pub/utilities/screen/
Alternatively, you can download the source code from:
http://www.gnu.org/software/screen/screen.html
However, most Unix-like distributions will include screen as part
of its default installation. The source code compilation is straightforward;
there are no configuration options, so just go to the source directory
and type:
./configure
make
make install
Read the documentation if you want to configure multi-user session
management.
Basic Usage
There are three methods of command-line invocation:
1. screen [ -options ] [ cmd [ args ] ]: For running specific
options and commands when screen is invoked for the first time.
2. screen -r [[pid.]tty[.host]]: Relates to attaching and
detaching from already running screen sessions.
3. screen -r sessionowner/[[pid.]tty[.host]]: For attaching/detaching
to existing sessions that are being run by other session owners.
Here are some example session invocations:
Start up screen with "vi" editing a file called "myfile.txt":
screen vi myfile.txt
Start up screen and give it the session name "admin". This is useful
when you plan on creating more than one running session:
screen -S admin
You can reset the history scrollback buffer to be 150 lines high (from
the default setting of 100) using this command:
screen -h 150
Initiating a screen session that starts "mc" (midnight commander)
on a remote machine through a secure connection can be achieved using
SSH (secure shell):
ssh -t -l myusername myhost screen mc
Session commands are bound by key combinations that always begin with
"C-a" (the <ctrl> and lowercase "a" buttons). Screen's online
help is invoked by typing C-a ?.
Describing each key-binding is beyond the scope of this article,
however, the following categories should give you an idea of what
the commands can accomplish:
Window usage -- Describes what you can do inside an individual
window. You can name a region, transmit command characters, and
log keyboard activity.
Window manipulation -- This involves creating, destroying, resizing,
and navigating windows. You can copy and paste text between windows,
as well as obtain summary information describing each window.
Session control -- Permits you to manipulate sessions such as
attaching and detaching sessions from the console.
Message control -- This controls the window messaging processing
such that you can monitor activities of one or more windows.
Access control -- You can password protect sessions and define
access permissions for the multi-user mode, which is similar to
the Unix standard of setting permissions (i.e., chown).
Example
The following example demonstrates basic screen usage. Let's walk
through a number of operations that involves three windows:
- Window "0" reads email
- Window "1" downloads and compiles source code
- Window "2" reads the source code documentation
To begin, log into an existing account:
ssh -t -l myaccount myserver screen -S admin -t email mutt
Screen's default behavior is to create a single window with a shell
running in it. In this case, the email client "mutt" is invoked in
the shell.
Notice that there are two "-t" switches used in the above command;
one is for ssh, and the second is for screen. They are not
related. The first "-t" switch, used in ssh, is meant to force pseudo-tty
allocation. Logging into a machine via ssh is normally not a problem,
but it gets complicated when a command on the remote server is invoked
at the same time in that you may get an error that says "Must be
connected to a terminal". The second "-t" switch is a screen-specific
command. It assigns the window title as "email". The session name
is given as "admin" using the "-S" switch.
Downloading and compiling the source code of interest will require
a second window, which is created with the following two-letter
combination: C-a c
Remember, "C-a" means pressing the <ctrl> button and lowercase
"a" together. There are other ways of creating a new window, because
screen uses many key-bindings to accomplish the same action. Navigating
between these two windows is accomplished by using: C-a n
or C-a <space>
We can see the two window titles by typing: C-a C-w
You can navigate directly to any window by simply highlighting
the window's title from this key-bound command: C-a "
At this point, both windows have the title of "email". The window's
title can be changed by typing: C-a A and then editing the
title "email" from the status bar. For the purposes of this article,
let's call it "postgres". Repeating C-a C-w will confirm
the change.
The next step is to download the source code:
wget ftp://ftp3.ca.postgresql.org/pub/source/v7.4/postgresql-7.4.tar.gz
(assuming, of course, that you already have wget installed on your
system). You can cycle over to the email window while waiting for
the download to complete.
Postgres has a lot of options, therefore, a third window is created
to be able to read from the INSTALL text file:
C-a c
The title of this window will be INSTALL:
C-a A install
Cycling through three windows to read the documentation and compose
the configuration command can make for a tedious process. A number
of commands and techniques permit navigation between the source code
window and the INSTALL documentation window, but my favorite method
is to "split" the console window into two regions:
C-a S
The top region displays the window that has the focus while the bottom
region is, for the moment, empty. Changing "focus" from the top region
to the bottom is accomplished by:
C-a tab
where "tab" is the TAB button.
You can cycle through all three windows in the bottom region with
C-a n. You will notice that the window titles are now visible.
It's easy to copy and paste between windows, and this is accomplished
by going into the copy mode: C-a [. You can highlight text
by pressing the spacebar at the beginning and once again at the
end of the string (See Figure 1). Writing the contents of the paste
buffer is done with:
C-a ]
After composing the configuration command, it's time to remove the
documentation window and restore the console to one window view. Place
the focus into the documentation region and "kill" this window with:
C-a k
Removing the now empty region is accomplished by changing the focus
to the still-active region -- the command-line shell -- which should
be the top one. Removing all other regions, except the current one,
is accomplished with:
C-a Q
Invoke the screen log function, which will hard copy the standard
output to a file called screenlog.x in the home directory (where x
is the assigned window identity number) before beginning the configuration
process of the postgres source code:
C-a H
Repeating the above command will stop window logging. There is
no limit on the number of windows you can log.
Terminating a screen session, closing all windows at the same
time, can be achieved this way:
C-a C-\
Sessions
Screen makes life a lot easier for admins who are always on the
move. Session management means you can do the following tasks:
List all running sessions and their status details (attached,
detached, dead):
screen -ls
Lockout a session. The only way back in is to type in the account
password:
C-a x
Invoke screen in detached mode to run background scripts:
ssh -t -l myaccount myserver screen -d -m -S script ~/myscript.sh
Detach a session from a terminal. This is Screen's defining
feature. It means you can leave a number of processes active and
allows you to log out of the account. You can do:
C-a d
or
screen -d [pid.tty.host]
This detaches the session identified as pid.tty.host. Or:
C-a D D
which will cause you to log out of your terminal, too.
Reattach a session to a terminal. You can also pick up a session
from an entirely different machine. Read the man page to learn
about all the possible variations for reattaching a session. Here's
a basic usage:
screen -r
which will reattach the first detached session in the list. Or,
you can do:
screen -d -r [pid.tty.host]
This detaches an already attached session identified as pid.tty.host,
which is obtained from screen -ls, and reattaches it to
this terminal.
Customization
Screen has a comprehensive command set that can be defined
at startup using initialization files. There are three traditional
locations for the screenrc files:
Global -- /etc/screenrc
Home account -- ~/.screenrc
User specific, which is specified on the command line when
screen is invoked -- screen -c myscreenrc
Environment variables can also be used to direct screen to
look for the screenrc in locations other than their defaults:
$SYSSCREENRC defines the global screenrc file
$SCREENRC and $HOME/.screenrc define the user specific screenrc.
Initialization files can set options, bind commands to keys, and
can even create multiple windows.
These commands, when placed in ~/.screenrc, will start
up a named session called "mysession", with three labeled (titled)
windows with their own process:
sessionname = mysession
screen -t midnight mc
screen -t top
screen -t myRemoteServer ssh -l myusername myRemoteServer
You can create your own shortcuts by binding keys to suit your
taste. For instance, bind K kill changes the kill command
from C-a C-k to C-a k.
These instructions are straight from the Debian distribution
of screen. They tell screen that the xterm has function keys
and to switch to a dark background:
termcapinfo xterm 'VR=\E[?5h:VN=\E[?5l'
termcapinfo xterm 'k1=\E[11~:k2=\E[12~:k3=\E[13~:k4=\E[14~'
termcapinfo xterm 'kh=\EOH:kI=\E[2~:kD=\E[3~:kH=\EOF:kP=\E[5~:kN=\E[6~'
Command Mode
Defining commands in the startup file is only one of two methods
of fine-tuning your screen sessions. You can also invoke commands
in a current screen session by invoking the "command-line mode"
followed by the command itself. All command-line instructions
begin with C-a :. For instance, you can change the color
of your bold text to red by typing:
C-a :
attrcolor b "R"
More information on available commands can be found in the screen
info page under "Command Summary".
Multi-User Sessions
You can use screen as the driving engine of a collaborative
environment; however, there's very little online information
on this subject. Multi-user sessions permit different users
to work on the same document, or process, at the same time.
Screen includes an entire suite of access control commands dealing
with users, groups, and window permissions. There are even mechanisms
that monitor window activity and share data across different
screen sessions.
This example goes through the steps of getting a multi-user
environment up and running between three users called "master",
"client1", and "client2", respectively.
Server
These instructions are put into the master's initialization
file, ~/.screenrc. Master will create four windows, as
follows:
- One for his exclusive use -- w_master
- One for the private use of client1 -- w_client1
- One for the private use of client2 -- w_client2
- A commonly accessed window -- w_common
All windows, except for the "w_master", will have the following
documents preloaded into their environment:
sessionname cool
screen -t w_master
screen -t w_client1 vim ~/tmp/client1.txt
screen -t w_client2 vim ~/tmp/client2.txt
screen -t w_common vim ~/tmp/common.txt
The next step is two add two users to the access control list
and to define their privileges with the command acladd
that takes a comma-delimited list of usernames:
acladd client1,client2
Defining privileges is accomplished using the command aclchg.
This command takes three arguments:
1. A comma-delimited list of users.
2. The permissions you would like to add.
3. The target window.
These permissions are expressed in the same format as the
standard Unix permissions (i.e., reading (r), writing (w), executable
(x)). Adding and removing permissions is accomplished using
+ and -:
aclchg client1,client2 -rwx w_master
aclchg client1 -rw w_client2
aclchg client2 -rw w_client1
This command enables the multi-user mode permitting user access
to the session:
multiuser on
Client
The client side of the multi-user screen session is accessed in
the following manner:
screen -x master/cool -p w_client1
You can see that "master" is the username, "cool" is the session
name and the '-p' switch accesses the window "w_client1".
The clients can use a split screen between w_common
and their own private one:
C-a S
C-a <tab>
c-a ' w_common
A Word about Security
Watch the permissions you set! The multi-session example is
not very strict on permissions because it still gives the clients
command-line capabilities (e.g., they can terminate the screen
session globally). There are a number of commands within screen
that can be use to fine-tune the security; it's a matter of
what you want to do.
Assigning permissions to groups rather than manipulating username
permissions will simplify your life. It's also a good idea to
put the screen session in a restricted environment, such as
the restricted mode under bash, or even to create a jail. Also,
look at the applications that are used in a screen session;
an editor like vim gives the added flexibility of restricting
commands only to those that are considered "safe" by using its
own initialization files.
Conclusion
There are many options, settings, and commands in screen,
and I've attempted to showcase its potential by addressing the
major features. The definitive references are, of course, the
man and info pages. Screen will also work with multi-character
fonts such as kanji and has a system called DOTSCREEN that permits
a direct interface connection with BRAILLE devices. As powerful
as it is, I don't see many systems administrators using screen
in their day-to-day activities. Perhaps some of them have never
heard of it, until now.
References
You can join the official discussion forum at: http://groups.yahoo.com/group/gnu-screen
The man page is pretty good, but the definitive document is
the screen info page.
Robert Bernier is a teacher and writer working in Canada's
capital region, Ottawa. He graduated from Lakehead University,
as a mechanical engineering technologist, and from the University
of Regina where he obtained his BSc in Systems Engineering.
He has been around computers since the days of the IBM 360 and
punch card hell, but only dedicated his professional career
exclusively to IT when he discovered Linux in the mid-90s. He
can be contacted at: robert.bernier5@sympatico.ca.
|