21 July 2007

GNU screen w/ ssh-agent

I maintain a lot of Linux servers, and I find it useful to keep an ssh session open to each one. But I don't want a terminal window open for each server, so GNU screen has been really helpful to me. I've used screen for years and I thought I knew most of its features, but I recently saw a post on polishlinux.org which has some really neat screen tricks which were new to me.

One screen trick I've used a lot in the past is to run screen inside of an ssh-agent session, with each screen window being an ssh session to one of my servers. So if I generate a password-protected ssh key and share it to all my servers, I can do the following:

$ screen -S wrapper -c .screenrc_escP
$ ssh-agent /bin/bash
$ ssh-add # supply ssh key password
$ screen -S ssh

The first call to screen sets up a 'wrapper' session, so that the ssh-agent will work for adding new windows to the inner screen session, even if I re-attach from another terminal. The .screenrc_escP configuration file contains escape ^Pp so that the two nested screen sessions have different escape sequences.

Then within the inner screen session, I can ssh to my servers without passwords (because I've already given the ssh key password).

The tedious part of doing this was manually opening all those ssh sessions and naming the screen windows. But now (thanks to the polishlinux.org post) I see that I can save something like the following to a file called .screenrc_ssh:

screen -t host1 ssh host1
screen -t host2 ssh host2
screen -t host3 ssh host3
screen -t host4 ssh host4

And then I can instead do this:

$ screen -S wrapper -c .screenrc_escP
$ ssh-agent /bin/bash
$ ssh-add # supply ssh key password
$ screen -S ssh -c .screenrc_ssh

And all my ssh sessions open like magic.

Another interesting part of the polishlinux.org post is the discussion of regions. This feature lets you split a screen window into regions. I've done this several times by accident, and I always just found it annoying, because I'd have to look in the man page to see how to close a region. I never knew how to use the feature. But you could have an ssh session to two servers in the two regions of the same window--allowing you to run some long-running process on one server and keep an eye on it while you're working on another server in the other region.

Screen rocks.

1 comment:

John said...

The auto ssh login frakin' rocks!