Automatic 'screen' on remote logins

If you routinely log into one or more remote systems using SSH, and have a flaky internet connection or an incompetent ISP, you probably already know about screen's ability to detach and reattach sessions.

However, you still have to manually type screen -r to resume a detached session, each time -- and sometimes you'll forget, start working in an SSH session, get logged out, and lose your state.

Here's the next step -- automatic screen-sessions for any remote logins.

Bonus features in the screenrc:

.bashrc

Add these lines at the top of ~/.bashrc on the target host:

# Auto-screen invocation. see: http://taint.org/wk/RemoteLoginAutoScreen
# if we're coming from a remote SSH connection, in an interactive session
# then automatically put us into a screen(1) session.   Only try once
# -- if $STARTED_SCREEN is set, don't try it again, to avoid looping
# if screen fails for some reason.
if [ "$PS1" != "" -a "${STARTED_SCREEN:-x}" = x -a "${SSH_TTY:-x}" != x ]
then
  STARTED_SCREEN=1 ; export STARTED_SCREEN
  [ -d $HOME/lib/screen-logs ] || mkdir -p $HOME/lib/screen-logs
  sleep 1
  screen -RR && exit 0
  # normally, execution of this rc script ends here...
  echo "Screen failed! continuing with normal bash startup"
fi
# [end of auto-screen snippet]

.screenrc

Create ~/.screenrc on the target host, containing:

# see http://www4.informatik.uni-erlangen.de/~jnweiger/screen-faq.html
# support color X terminals
termcap  xterm 'XT:AF=\E[3%dm:AB=\E[4%dm:AX'
terminfo xterm 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX'
termcapinfo xterm 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX:hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'
termcap  xtermc 'XT:AF=\E[3%dm:AB=\E[4%dm:AX'
terminfo xtermc 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX'
termcapinfo xtermc 'XT:AF=\E[3%p1%dm:AB=\E[4%p1%dm:AX:hs:ts=\E]2;:fs=\007:ds=\E]2;screen\007'

# auto-screen support; see http://taint.org/wk/RemoteLoginAutoScreen
# detach on hangup
autodetach on
# no startup msg
startup_message off
# always use a login shell
shell -$SHELL

# auto-log
logfile $HOME/lib/screen-logs/%Y%m%d-%n.log
deflog on

Note: if you just want the auto-screen feature, the middle 7 lines are the important bit; you can probably omit the "color X terminals" and "auto-log" stanzas if you like.

Credits

kaspar notes that 'it's better to check for 'SSH_TTY' than 'SSH_CLIENT', as the latter is trying to start screen on 'scp' and 'sftp' connections, too, which is breaking them.' Fixed.

RemoteLoginAutoScreen (last edited 2006-08-26 13:09:59 by 213-202-176-135)