Skip to content

Instantly share code, notes, and snippets.

@ozars
Last active September 23, 2018 20:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozars/b461ed806667a2a08087acd1563c99e8 to your computer and use it in GitHub Desktop.
Save ozars/b461ed806667a2a08087acd1563c99e8 to your computer and use it in GitHub Desktop.
Convenient ssh-agent and forwarding configuration

If you'd like to ensure only one instance of ssh-agent is working in background, add this to your .bashrc (or .zshrc if you are using zsh):

function setup_ssh_agent {
  local SSH_AGENT_DATA
  local SSH_AGENT_RUN_NEW
  local SSH_AGENT_CMD_LINE
  # If there is no active agent
  if [ -z "$SSH_AUTH_SOCK" ]; then
    # See if there is session from previous ssh-agent run
    SSH_AGENT_DATA=$(2>/dev/null cat ~/.ssh_agent_data)
    if [ $? != 0 ]; then
      # If there is no previous session, run ssh-agent
      SSH_AGENT_RUN_NEW=1
    else
      # Load previous session var
      eval "$SSH_AGENT_DATA" > /dev/null
      # If agent is not set or it is dead, run ssh-agent
      SSH_AGENT_CMD_LINE=$(2>/dev/null tr '\0' ' ' < /proc/$SSH_AGENT_PID/cmdline)
      if [ $? != 0 ] || [ "$SSH_AGENT_CMD_LINE" != "ssh-agent -s " ] || [ -z "$SSH_AUTH_SOCK" ] || [ ! -e "$SSH_AUTH_SOCK" ]; then
        SSH_AGENT_RUN_NEW=1
      fi
    fi
    
    # Run new ssh-agent if needed
    if [ "$SSH_AGENT_RUN_NEW" == 1 ]; then
      SSH_AGENT_DATA=`ssh-agent -s`
      eval "$SSH_AGENT_DATA" > /dev/null
      # Save configuration for next terminal sessions
      echo "$SSH_AGENT_DATA" > ~/.ssh_agent_data
      # Set file's permission to user r/w only
      chmod 600 ~/.ssh_agent_data
    fi
  fi
}

setup_ssh_agent # Don't forget to call above function!

To automatically add keys when you use them with ssh, use AddKeysToAgent configuration. To forward your ssh-agent to sessions you access through ssh, use ForwardAgent option.

Example configuration from .ssh/config for these two:

Host *
     AddKeysToAgent yes
     ForwardAgent yes

This should be enough for a nice working ssh-agent!

Note 1: Forwarding your agent in all ssh sessions may not be secure. You may want to use spesific hostnames for ForwardAgent in your config, instead of a wildcard hostname. Same goes with AddKeysToAgent configuration.

Note 2: This gist assumes that you need just one ssh-agent. You may use multiple ssh-agent to keep separate set of keys, which is an advanced use of ssh-agent. This gist does not handle this case.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment