Automatic Screen for SSH Login

You can enhance your SSH experience by automatically starting a screen or byobu session when you log in via SSH. This can help you maintain your sessions, especially when working on remote servers. Here’s how to set it up:

  1. Edit Your ~/.bashrc File: Open your ~/.bashrc file for editing using your preferred text editor. You can use a command like nano ~/.bashrc or vim ~/.bashrc.

  2. Add the following code snippet to the end of your ~/.bashrc file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#======================================================================
# 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) or byobu session. Only try once
# -- if $STARTED_SCREEN is set, don't try it again, to avoid looping
# if screen or byobu 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
  # Try starting byobu first, if available
  if command -v byobu &>/dev/null; then
    byobu && clear && exit 0
  fi
  # If byobu is not available, try starting screen
  screen -x && clear && exit 0
  if [ "$?" != "0" ]; then
    screen && clear && exit 0
  fi
  # Normally, execution of this rc script ends here...
  echo "Screen or byobu failed! Continuing with normal bash startup."
fi
# [end of auto-screen snippet]
# ======================================================================
  1. Save and Exit: After adding the code, save the changes to your ~/.bashrc file and exit the text editor.

  2. Apply Changes: To apply the changes to your current session without logging out, you can run the following command:

1
source ~/.bashrc
  1. Using Screen or Byobu:
    • When you SSH into your server in the future, it will automatically start a screen or byobu session if it’s an interactive SSH session.
    • To disconnect from your SSH session while inside screen or byobu, use the following key combination: Ctrl-a followed by d. This will detach your session, allowing you to reattach to it later.

Now, every time you SSH into your server, you will be placed into a screen or byobu session automatically, providing you with a more resilient and flexible terminal environment.

0%