10

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.

Pete Ashdown
  • 3,230

4 Answers4

9

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 $@
}
Pete Ashdown
  • 3,230
7

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
}

 

Relsqui
  • 71
1

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 https://superuser.com/a/1114257/42546. I'm not sure what the proper StackOverflow etiquette is for coping answers across various StackExchange sites.)

1

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

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