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:


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

# Auto-screen invocation. see:
# 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_CLIENT:-x}" != x ]
  [ -d $HOME/lib/screen-logs ] || mkdir -p $HOME/lib/screen-logs
  screen -xRR && exit 0
  # normally, execution of this rc script ends here...
  echo "Screen failed! continuing with normal bash startup"
# [end of auto-screen snippet]


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

# see
# 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
# 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.

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