Doing an Ssh-Add Upon Ssh/Slogin If Key Is Not in Ssh-Agent?

When I'm running Gnome, ssh-agent will run ssh-add upon slogin/ssh if the identity is not loaded. I want to mimic this behavior on remote shells, but everything I find suggests to run ssh-add upon login. I only want to run ssh-add if I subsequently run slogin/ssh on the remote shell, not every time I login.

4 Answers

I worked out a solution for this via the bash shell.

Add to .bashrc:

check-ssh-add() {
if [ "$DESKTOP_SESSION" == "" ]; then
  if [[ `ssh-add -l` != *id_?sa* ]]; then 
    ssh-add -t 5h  ## 5 hour ssh-agent expiration
  fi
fi
}

slogin() {
check-ssh-add
/usr/bin/slogin $@
}

ssh() {
check-ssh-add
/usr/bin/ssh $@
}

scp() {
check-ssh-add
/usr/bin/scp $@
}

sftp() {
check-ssh-add
/usr/bin/sftp $@
}

There's actually an even simpler way. ssh-add -l returns true (0) if there are keys and false (1) otherwise, so your first function can be replaced with this:

check-ssh-add() {
  if ! ssh-add -l >/dev/null; then
      ssh-add -t 5h
  fi
}

Even simpler in the «this is an interactive session» part add

ssh-add -l &> /dev/null || ssh-add ~/.ssh/my_id

Newer versions of OpenSSH can add the key to the agent on first use, if you enable AddKeysToAgent yes in your ~/.ssh/config.

(I've learned this from . I'm not sure what the proper StackOverflow etiquette is for coping answers across various StackExchange sites.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Elena Rostova

Elena Rostova

Lead Health, Wellness & Medical Journalist

Elena Rostova holds a Master's degree in Public Health Journalism. She covers groundbreaking medical research, holistic wellness trends, mental health awareness, and nutritional science.

Share this article
Twitter Facebook Pinterest